Programming a Guessing Game in Rust!

Поділитися
Вставка
  • Опубліковано 2 жов 2024

КОМЕНТАРІ • 138

  • @letsgetrusty
    @letsgetrusty  3 роки тому +8

    📝 Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet

  • @NoelTanner
    @NoelTanner 2 роки тому +182

    Stuck at 5:55? The 2021 syntax for rng.gen_range has changed to two periods rather than a comma: "let secret_number = rand::thread_rng().gen_range(1..101);" Stay rusty my friends!

    • @rudhydacosta6446
      @rudhydacosta6446 2 роки тому +9

      You are a God amongst humans! 🛐

    • @aldolhitlercondensation1363
      @aldolhitlercondensation1363 2 роки тому +3

      That wouldn't be an issue if you follow along with the version of the dependency used in this video (where cargo shines). I feel the serires is more about getting the core of rust right rather than the crate functionalities.

    • @petercosta1883
      @petercosta1883 Рік тому

      omg thank u so much

    • @maximus1172
      @maximus1172 Рік тому +9

      (1..100) means 1 inclusive and 100 exclusive,
      (1..=100) means 1 inclusive and 100 also inclusive, so this one is equivalent to (1..101)

    • @sofianekhoudour
      @sofianekhoudour 7 місяців тому

      yes it changed, i would do it this way :
      let range = Range::new(1, 101);
      let rang_number : i32 = rand::thread_rng().sample(range);
      println!("Random number: {}",rang_number);

  • @GolangDojo
    @GolangDojo 3 роки тому +54

    Immuatable by default - that's pretty sweet

    • @kevinmcfarlane2752
      @kevinmcfarlane2752 3 роки тому +2

      That part is familiar if you’re coming from F#, even down to the syntax.😊

    • @indranishome9003
      @indranishome9003 3 роки тому +13

      Not sweet for Java C++ programmers tho. However, using it straight for a week gets your mind wrapped around the Rustic beauty.

    • @quebirt
      @quebirt 5 місяців тому

      Immutable by default has some major benefits, but it's not free. It comes with a lot of its own issues and if you are old enough to remember moving to OOP and getting in to that mindset, this is A LOT more to get ahold of than OOP was.

    • @Simple_OG
      @Simple_OG 4 місяці тому

      Yup is soo good

  • @letsgetrusty
    @letsgetrusty  3 роки тому +23

    Don't forget to remove the line which prints the random number ;)

  • @sleepymarauder4178
    @sleepymarauder4178 3 роки тому +24

    Complementing the book with this is really great. Thank you

  • @arshsharma9555
    @arshsharma9555 3 роки тому +43

    For those getting a thread panic after entering the second number make sure the declaration for guess
    let mut guess = String::new();
    goes inside the loop. It's not specified in the docs.
    Not sure why it needs to be declared for every iteration of the loop.

    • @31redorange08
      @31redorange08 3 роки тому +23

      Because the string gets filled with each call to read_line(). Add println!("{:?}", guess) and you'll see it. You could also call guess.clear() to empty the string.

    • @lupsik1
      @lupsik1 2 роки тому +1

      @@31redorange08 wasnt it because we redeclared guess as u32 and it just stayed that way?
      or i just encountered a diff. situation

    • @jabuci
      @jabuci 2 роки тому +5

      If, for instance, you provide 100, the string will hold "100
      ". If you read then 2, it's added to the string, thus it becomes "100
      2
      ".

  • @turbo6780
    @turbo6780 2 роки тому +4

    Just started learning Rust. C++ and Go used to be my primary tools to work with. After learning about Rust it has convinced me that this could potentially be the future when it comes to high performance applications. I still sort of miss the comfortable syntax in Go though :D

  • @codychan4992
    @codychan4992 2 роки тому +13

    This is a very informative video, love it. Thanks.
    // 1. use rand crate to generate a random number
    // 2. use std::io to read input, trim()
    // 3. convert a variable to another type using something like :u32
    // 4. use std::cmp compare two variables
    // 5. loop(continue+break)
    // 6. match
    // 7. Result type
    // 8. use colored crate to print text in colors

  • @sahilverma4077
    @sahilverma4077 3 роки тому +15

    i like the idea of giving colour to the text, we don't normally do that

  • @Xenoxanite
    @Xenoxanite Рік тому

    Finally i succes to find a good rust tutorial playlist.

  • @richsadowsky8580
    @richsadowsky8580 2 роки тому +2

    Thanks Bogdan. I had to work through some syntax errors or the a few things but got it working. I had to comment out the .expect() on the read_line. I also had to change the first match:
    guess.trim().parse::() {
    OK(num: u32) => num,
    Err(_) => continue,
    };
    I know the parse change is called the Turbofish syntax, and not sure what your original Ok case did but this is what worked. I'm using rustc 1.61.0 (fe5b13d68 2022-05-18).
    Suggestion: possibly link to a gist or other place to get the code.

  • @madhank93
    @madhank93 3 роки тому +2

    Thank you !!! Please keep up the good work

  • @johk2293
    @johk2293 Рік тому

    Match with Ordering looks genius. And that's only the beginning. I like this language already. Coming from TypeScript and Python world

  • @vhmolinar
    @vhmolinar 3 роки тому +14

    Learning Rust while washing dishes. That is just great!

  • @productivewallace
    @productivewallace 3 роки тому +2

    The poke lol. Imma steal that

  • @markdaniels4389
    @markdaniels4389 2 роки тому

    Thanks for what you are doing brother. Peace & prosperity to your people.

  • @spyboy3924
    @spyboy3924 Місяць тому

    nice explanation 🙌

  • @g-kkone1662
    @g-kkone1662 3 роки тому

    Great material !
    Keep doing it it helps a lot!

  • @erwinschrodinger2320
    @erwinschrodinger2320 3 роки тому +3

    Thank you!

  • @FM-xz4gz
    @FM-xz4gz 5 місяців тому +1

    is the syntax changed?
    use std::io;
    fn main() {
    println!("Guess the number!");
    println!("Please input your guess.");
    let mut guess = String::new();
    io::stdin()
    .read_line(&mut guess)
    .expect("Failed to read line");
    println!("You guessed: {}", guess);
    }

  • @MrSerler
    @MrSerler Рік тому

    thank you so much. great tutorial.

  • @LEADER_of_CLANSE
    @LEADER_of_CLANSE 29 днів тому

    When i looked this up i didn't think it meant this rust

  • @callbettersaul
    @callbettersaul Рік тому +1

    Isn't rng in that context Random Number Generator?

  • @__-_-__-_--_
    @__-_-__-_--_ 7 місяців тому

    just importing the "colored" library added those "red" and "green" methods to String?
    i have only seen this before in JS when you modify the Prototype of the build-in objects. It looks very hack-y, but i guess the typing and compiler checks makes it okay.

  • @matthijshebly
    @matthijshebly 7 місяців тому +1

    "rng" isn't "range". It's "random number generator".

  • @RhymesWithPorridge
    @RhymesWithPorridge 3 роки тому +2

    That first code to test doesn't even remotely compile on my machine! I copied it exactly from what I see on your screen, but I get a ton of errors. For example:
    io::stdin(): Stdin
    generates the error "casts cannot be followed by a method call". Then we have
    .expect(msg: "Failed to read input");
    generates the error "expected type, found "Failed to read input""

    • @w___s
      @w___s 3 роки тому +5

      That's because of the IDE he's using. It interjects extraneous garbage which breaks the code if you simply copy everything you see. This was a terrible choice for teaching and you have discovered why! See the online rust book and copy what's there instead.

  • @linjianru
    @linjianru 2 роки тому

    excellent video! thank you!

  • @pepijnvandijke2134
    @pepijnvandijke2134 3 роки тому +3

    you import rand::Rng and then use rand::thread_rng() how does that work?

    • @letsgetrusty
      @letsgetrusty  3 роки тому +4

      "use rand::Rng" is importing the Rng trait. The Rng trait defines methods that random number generators implement, and this trait must be in scope for us to use those methods.

  • @andresdallarizza1526
    @andresdallarizza1526 Місяць тому

    amazing shit bro

  • @ibrahimmohammed3484
    @ibrahimmohammed3484 2 місяці тому

    me when i finish the game: le ruste developer

  • @MobiusCoin
    @MobiusCoin Рік тому +1

    Okay, coming from TypeScript, the match syntax is a bit weird, gonna have to get used to that one. And I "know about" floats but I never really thought about numbers being like... signed or unsigned bits, gonna have to really consciously think about that now.

  • @zoodiacdiablo
    @zoodiacdiablo Рік тому +1

    Thanks so much for this tutorial!! It gives a nice preview of what Rust is capable of doing. Really cool! I have one question. Why do you want to use ordering instead of just using size comparison with condition? Wouldn't it be simpler to understand? Is there an advantage for using ordering??

  • @terentyrezman7252
    @terentyrezman7252 3 роки тому +3

    it seems that `use std::io` does not actually import anything like #include in c++ or import in python does, it just makes shorter syntax for calling things from that modules like `io::stdin()` instead of writing `std::io::stdin()`, but withot `use` the longer version still works

    • @letsgetrusty
      @letsgetrusty  3 роки тому +4

      That's correct. "A use declaration creates one or more local name bindings synonymous with some other path."
      source: doc.rust-lang.org/reference/items/use-declarations.html

    • @DonGioification
      @DonGioification 3 роки тому

      Surely though at compilation time the library is included in the binary as it needs the code to work? So practically it’s not really different

    • @mistakenmeme
      @mistakenmeme 3 роки тому

      It's similar to C++ "using namespace std;"

  • @israaaelghazawy1719
    @israaaelghazawy1719 3 роки тому +2

    Thank you sir , you have Awesome explanation for Rust. please keep up your work.

  • @MattTrevett
    @MattTrevett 26 днів тому

    If you're having problems it may be a difference in versions, especially in the cargo.toml or Rust version you're using. If you have any problems, try popping the code into Chat GPT and it'll help you along the way, but it doesn't always recognize that a different version is being used.

  • @Chuukwudi
    @Chuukwudi 3 місяці тому

    If you're watching in June 2024 or later, You might need dependency: rand = "0.8.5"
    It no longer supports double comma separated arguments. Only gen_range(low..high) and gen_range(low..=high) are supported. Notice the dots and equal signs. No commas.

  • @Nerpson
    @Nerpson 3 роки тому +1

    I installed the rust-analyser extension, but for some reason i have no linter nor help popups...

  • @Libellisth
    @Libellisth 2 місяці тому

    Thank you, your crash course together with the vids from the user 'No Boilerplate'; they help me greatly to get up to speed with Rust. What a great language. I would suggest howver to turn off your IDE's typehinting when you record these demo's.

  • @foobar1269
    @foobar1269 2 роки тому +1

    gen_range(1..101);

  • @quebirt
    @quebirt 5 місяців тому

    I'm not a fan of the rust-analyzer at all. I don't like to have things added that I didn't type and it is AGGRESSIVE AF. I'm sure it's great if you learn around it and use it daily. Probably saves a load of keystrokes and helps prevent errors and all that, but not this old man. Intellisense is one thing, where I'm seeing the options and hitting tab or something to use them, but having this thing change code on another line when I type (or typo) something is aggravating. Call me old, but I don't want anything changing my code when I'm not telling it to.

  • @johnvonhorn2942
    @johnvonhorn2942 Рік тому

    Geez, this is hard going. I tried importing the latest version of "rand" in cargo.toml and, "yep", it broke the program, saying that gen_range now just takes one number, not two.
    Then we have two variables called "guess", one is a string and the other is a 32 bit int? If Rust is so concerned about safety why would it allow two different variables to have the same name?
    Finally why the hell am I having to use the standard library's "cmp" to compare things when an "if" statement or a "case" statement is just so much more readable and cleaner?
    Rust strikes me as an autistic language for masochists. We could just write clean, clear, concise code or we could use Rust and have to fuss over pedantic syntax that just looks damn ugly.
    Okay, just Googled, "Does Rust have an 'if' keyword?" and it does! Not sure why Bogdan took us off road, to me it looks ugly. He's joyriding us around the houses.
    I'll try and stick with Rust but it's going to be a painful learning curve.

  • @2002budokan
    @2002budokan 2 роки тому +1

    God bless you, man. Instead of reading(&sleeping) I watch full aware and within 10mins chapters are completed.

  • @puvididdle
    @puvididdle 2 роки тому

    haha the sign at the back looks like "lets get busty". thank you for the lesson.

  • @tsdineshjai8565
    @tsdineshjai8565 5 місяців тому

    @1:00 The author mentioned "language server". Can anyone elucidate, as I couldn't comprehend. Where do we have to install it ?

  • @FaithOlusegun
    @FaithOlusegun 2 роки тому

    Hold up! This 'match' expression ... Is it like Switch statements as in other programming languages? I see match expression everywhere in rust.

  • @kendlemintjed7571
    @kendlemintjed7571 4 місяці тому

    you really shouldnt pronounce rng as range, since it stand for random number generation, it only leads to confusion

  • @Soulis98
    @Soulis98 2 роки тому +2

    How do you get the extra info of i32, high, low, etc...?

  • @varad.h8
    @varad.h8 6 місяців тому

    Even if we type "quit", game just continues, what abt that? like we can't quit until we get the guess correct.

  • @marcosignoretto1150
    @marcosignoretto1150 4 місяці тому

    For those who are watching it from 2024, after stdin() and read_line the colon is no longer required to wrap a line

  • @lcssbr
    @lcssbr Місяць тому

    It only worked for me after I cleaned the buffer in every loop interaction, otherwise it always failed to parse after the first loop interaction.

  • @engineertrooper
    @engineertrooper 2 роки тому

    Which plugin is used to display the docu snippets? Example: 1:56
    Nice video :3
    Short and limited to the interesting stuff.

  • @jaykrown
    @jaykrown 7 місяців тому

    Something confusing me are the semicolons after the curly brackets, they seem almost arbitrary. The .parse() method requires them, but then the .cmp method does not? Why doesn't the loop require them either?
    Exactly why does this require a semicolon after the curly bracket
    let guess: i32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue
    };
    ...and this doesn't?
    match guess.cmp(&secret_number) {
    Ordering::Less => println!("Too small."),
    Ordering::Greater => println!("Too big."),
    Ordering::Equal => {
    println!("You win!");
    break;
    }
    }

    • @jaykrown
      @jaykrown 7 місяців тому

      Ok I looked it up. Rust only requires a semi-colon after the curly braces specifically when it's an assignment, such as using the term "let". Why? No idea, but that's it.

  • @venkateswarans1012
    @venkateswarans1012 Рік тому

    Hmm just wounder how rust allows to declare same variable named "guess" two times 😮

  • @spootdev
    @spootdev 3 роки тому +3

    In your cargo file you have rand v0.5.5.....but cargo compiled v0.5.6 instead. Is this an editing boo-boo or does Cargo override the deps version if it feels like it?

    • @letsgetrusty
      @letsgetrusty  3 роки тому +3

      Not an editing boo-boo lol. This is a great call out! Cargo understands Semantic Versioning and "0.5.5" is actually short-hand for "^0.5.5" which means we should get the latest patch release. That's why cargo installed "0.5.6".

    • @mateocid
      @mateocid 3 роки тому +1

      @@letsgetrusty You are right! I would just add that cargo does "^0.5.5" only for the same release version which supports backwards compatibility. Therefore, if there is a release version "1.0", cargo won't use it, it will only use the latest release under "0.X" versions. Noting that the first number in the version always implies major changes and therefore, not guaranteed backwards compatibility support. Thank you for your videos!

  • @jaromor8808
    @jaromor8808 2 роки тому +1

    maybe you could have explained how come that suddenly you can call methods like red() on a String
    my guess is that the colored package somehow adds those methods on String...? but i think it'd be worth mentioning

    • @nikoladd
      @nikoladd 2 роки тому

      The library implements traits with those methods for string. Also it's not String, but str that it's being called on. Those are different types.

  • @inserteunnombreapropiado9079

    So far, Rust looks scarier than C++ or C. Still, I'm committed to learning it.
    This is the same but in Lua:
    print("Guess the number!")
    local secret = math.random(1, 100)
    while true do
    print("Input a number")
    local guess = tonumber(io.read())
    if guess then
    if guess < secret then
    print("Too small!")
    elseif guess > secret then
    print("Too big!")
    else
    print("You guessed!")
    break
    end
    end
    end

  • @mathewhull222
    @mathewhull222 2 роки тому +1

    i learned alot from this it was a really jam packed video for me

  • @cerealbowl7038
    @cerealbowl7038 6 місяців тому

    The colors are not working. I am not getting any errors, but the text is still white.

  • @blaises8221
    @blaises8221 8 місяців тому

    what vs code extension are you using

  • @TwstedTV
    @TwstedTV 2 роки тому

    You completely lost me in this video. The first video I was following along just fine.
    Until I got into this video. feels like I got pushed off a cliff and told to fly with no wings. 🤷‍♀
    I have to hunt down another tutorial video. Maybe ill come back some other time once I get a grip on Rust fundamentals. thanks anyways 🙃

  • @LukesOffline
    @LukesOffline 3 роки тому +1

    I can't understand why but my loop block is not working.

  • @notoriousjdj
    @notoriousjdj 3 роки тому +1

    What VSCode extension are you using that is inserting inline code info? (edit: I'm guessing it is rust-analyzer(?);I had installed it recently, but it wasn't until I exited and reopened VSCode that I saw those inline helper statements as well).

  • @learningchannel3362
    @learningchannel3362 2 місяці тому

    damn. you're giving more content in less time. you're amazing bro. thanks for teaching Rust

  • @harshpreetweb3
    @harshpreetweb3 9 днів тому

    thanks for this video

  • @sebastianbergt3249
    @sebastianbergt3249 2 роки тому

    these days a new version fo rand is around, which uses ranges: likes so "rand::thread_rng().gen_range(1..10);"
    rand = "0.8.4"

  • @mathewhull222
    @mathewhull222 2 роки тому

    the syntax errors are killin me omfg, figured it out, some stuff autofills depending on the functions you use like you diddnt type the 'Result' bit

  • @soberhippie
    @soberhippie 2 роки тому

    It's just so annoying that they didn't throw away the bloody semicolons in the twenty-f*ing-first century! Great videos. Thank you very much!

  • @redcrafterlppa303
    @redcrafterlppa303 2 роки тому

    As a first look at rust it looks like a mix of js, c++ and c# with something extra and a mangled Syntax. That's not negative!! C++ is a great language but sometimes has a weird Syntax. It lacks some high level stuff and has some sharp corners. The only real criticism on rust I have right now is its overuse of enums. An exception system like in java or c# would have fit better.

  • @Tom-JS
    @Tom-JS Рік тому

    Is rust readying for gui

  • @oihandeshayes6751
    @oihandeshayes6751 10 місяців тому

    an update would be awesome

  • @arkaprovobhattacharjee7044
    @arkaprovobhattacharjee7044 2 роки тому

    coming from the java background the ownership part is a little confusing.

  • @perrinms
    @perrinms Місяць тому

    What version of rust are you using? I have rustc and cargo 1.80.1. This won't compile.

  • @exoticcoder5365
    @exoticcoder5365 3 роки тому +1

    Hi, Thank you for your video, I have one thing to ask , I use "cargo run", it works, but when I use the shortcut "control + option(alt) + N" to run the code in VScode , it doesn't work ( many errors : colour , rand , etc ), what's the difference? or why ?

    • @letsgetrusty
      @letsgetrusty  3 роки тому

      I haven't tried using keyboard shortcuts for cargo run. Did you configure that yourself?

    • @exoticcoder5365
      @exoticcoder5365 3 роки тому

      @@letsgetrusty I googled the VScode shortcut for running codes sometimes ago, It works for Python, C++, even Rust projects for me until this chapter, but nevermind It's not important, just wondering if you know why it doesn't work this time

  • @turbasdd
    @turbasdd 2 роки тому

    on the second match statement, my code works with and without the end comma after the close curly brackets...
    Shouldn't it throw an error?

  • @chairmakerPete
    @chairmakerPete 2 роки тому

    Really enjoying this series. Great teacher, pace is good, and examples that iteratively build on themselves like this are great.
    I forgot to add the use colored::* statement at the top of my main.rs file, but everything still worked with the .red() and .green() methods on the static strings.
    When I did add "use colored::*;" to the top of the program, it got a yellow squiggly and 'cargo run' complained it was an "unused import", but the program ran anyway. Chopping off the "::*" at the back of the "use colored" statement fixed it, but clearly this is just some syntactic sugar. Sure all will be revealed soon.
    On to the next one.

  • @dabunnisher29
    @dabunnisher29 6 місяців тому

    Your channel really is the best Rust Language Channel. Thank you so much for all that you do.

  • @alwaysgood3913
    @alwaysgood3913 2 роки тому

    Can anyone tell me why the following code
    let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => {
    println!("Please enter only positive integers");
    continue;
    }
    };
    works only in a loop?
    Without a loop it shows the error:
    mismatched types
    expected `u32`, found `()`rustcE0308

    • @paulzupan3732
      @paulzupan3732 Рік тому

      The `continue' keyword doesn't really have any meaning outside of a loop

  • @RussianConnection22
    @RussianConnection22 Рік тому

    Watching this in August 2023 - good addition with colored. This is a great tutorial to follow along with the book - thanks!

  • @zbjz
    @zbjz 2 роки тому

    Fantastic video!
    What chair are you using?
    What camera are you using?

  • @louisdreibeiner6104
    @louisdreibeiner6104 2 роки тому

    When I copy and paste the dependency rand it doesn’t build it in the console like by you (5:03). It seems like my cargo.toml is just a text, it doesn’t look like a code.

  • @cxl2377
    @cxl2377 2 роки тому

    Hi! can you tell me the VS code extension that defines the commands ure using?

  • @kodedrhema2288
    @kodedrhema2288 2 роки тому

    Yo I enjoy learning Rust because of your videos. The example you use, perfect...

  • @imadbkr1493
    @imadbkr1493 Рік тому

    Thank you so much for your videos man I like how you teach it's super clear for me!

  • @mritunjaymusale
    @mritunjaymusale 2 роки тому

    4:41 for new viewers use "cargo add " in a terminal

  • @unknown-user001
    @unknown-user001 2 роки тому

    this is awesome for a lazy person like me.

  • @jakubrembiasz8942
    @jakubrembiasz8942 8 місяців тому

    A M A Z I N G! I need more, hahaha. Great work buddy!

  • @surykmvar
    @surykmvar 2 роки тому

    Am getting an error but my code is right can u help me

  • @erlangparasu6339
    @erlangparasu6339 2 роки тому

    i dont understand, guest is i32, but return continue

  • @gabrielmengassodefranca1615
    @gabrielmengassodefranca1615 3 місяці тому

    🔥🔥🔥🔥🔥🔥🔥🔥🔥

  • @PejmanRezaei-qv9lt
    @PejmanRezaei-qv9lt 8 місяців тому

    simplifying things is a great skill. thanks

  • @chrishabgood8900
    @chrishabgood8900 Рік тому

    how do you get the run debug buttons to show up?

  • @hesam-init
    @hesam-init 2 роки тому

    ur videos are great and perfect thanks :)

  • @MrKB_SSJ2
    @MrKB_SSJ2 11 місяців тому

    9:50

  • @gayansenaratne8001
    @gayansenaratne8001 2 роки тому

    Thanks a lot! This is really helpful.

  • @bjugdbjk
    @bjugdbjk 2 роки тому

    Wow, I just love this playlist !!

  • @phil86_
    @phil86_ 2 роки тому

    Very interesting intro example

  • @roberthawaiian1542
    @roberthawaiian1542 2 роки тому

    Hi, what extension creates the gui that explains all the crate variables from rand?

    • @roberthawaiian1542
      @roberthawaiian1542 2 роки тому

      Nevermind, installed the official rust extension and works fine now. (was using the alternative one)

  • @cyrilanisimov
    @cyrilanisimov 2 роки тому

    Thanks!

  • @arsil_
    @arsil_ 2 роки тому

    Awesome video mate!

  • @BrainbiteYT
    @BrainbiteYT 2 роки тому

    when I make a range 5:27 it doesn't come up with low and high

    • @onikiller10
      @onikiller10 2 роки тому

      The syntax has changed since the making of this video, you are supposed to do (1..101) now. Found it out thanks to rust-analyzer.