Programming a Guessing Game in Rust!

Поделиться
HTML-код
  • Опубликовано: 13 июл 2024
  • The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.
    📝 Get notified when the Rust Cheatsheet comes out: letsgetrusty.com/
    The Rust book: doc.rust-lang.org/stable/book/
    0:00 Intro
    0:35 Creating Project
    1:07 User Input
    4:30 Random Numbers
    8:44 Game Loop
    9:52 Handling Invalid Input
    11:42 Adding Color
    12:50 Outro
    #letsgetrusty #rust #tutorial
  • НаукаНаука

Комментарии • 128

  • @letsgetrusty
    @letsgetrusty  3 года назад +7

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

  • @NoelTanner
    @NoelTanner 2 года назад +170

    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 Год назад +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 Год назад +8

      (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 4 месяца назад

      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 года назад +52

    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 года назад +14

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

    • @quebirt
      @quebirt 2 месяца назад

      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 2 месяца назад

      Yup is soo good

  • @letsgetrusty
    @letsgetrusty  3 года назад +22

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

  • @sahilverma4077
    @sahilverma4077 3 года назад +14

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

  • @vhmolinar
    @vhmolinar 3 года назад +14

    Learning Rust while washing dishes. That is just great!

  • @arshsharma9555
    @arshsharma9555 3 года назад +42

    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 2 года назад +22

      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
      ".

  • @sleepymarauder4178
    @sleepymarauder4178 3 года назад +23

    Complementing the book with this is really great. Thank you

  • @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

  • @2002budokan
    @2002budokan 2 года назад +1

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

  • @g-kkone1662
    @g-kkone1662 2 года назад

    Great material !
    Keep doing it it helps a lot!

  • @dabunnisher29
    @dabunnisher29 4 месяца назад

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

  • @madhank93
    @madhank93 3 года назад +2

    Thank you !!! Please keep up the good work

  • @imadbkr1493
    @imadbkr1493 Год назад

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

  • @bjugdbjk
    @bjugdbjk 2 года назад

    Wow, I just love this playlist !!

  • @israaaelghazawy1719
    @israaaelghazawy1719 3 года назад +2

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

  • @arsil_
    @arsil_ 2 года назад

    Awesome video mate!

  • @RussianConnection22
    @RussianConnection22 10 месяцев назад

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

  • @mathewhull222
    @mathewhull222 2 года назад +1

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

  • @markdaniels4389
    @markdaniels4389 2 года назад

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

  • @jakubrembiasz8942
    @jakubrembiasz8942 5 месяцев назад

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

  • @kodedrhema2288
    @kodedrhema2288 2 года назад

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

  • @Xenoxanite
    @Xenoxanite 11 месяцев назад

    Finally i succes to find a good rust tutorial playlist.

  • @gayansenaratne8001
    @gayansenaratne8001 2 года назад

    Thanks a lot! This is really helpful.

  • @turbo6780
    @turbo6780 Год назад +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

  • @MrSerler
    @MrSerler Год назад

    thank you so much. great tutorial.

  • @hesam-init
    @hesam-init 2 года назад

    ur videos are great and perfect thanks :)

  • @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.

  • @PejmanRezaei-qv9lt
    @PejmanRezaei-qv9lt 5 месяцев назад

    simplifying things is a great skill. thanks

  • @linjianru
    @linjianru 2 года назад

    excellent video! thank you!

  • @cyrilanisimov
    @cyrilanisimov 2 года назад

    Thanks!

  • @erwinschrodinger2320
    @erwinschrodinger2320 3 года назад +3

    Thank you!

  • @productivewallace
    @productivewallace 3 года назад +2

    The poke lol. Imma steal that

  • @johk2293
    @johk2293 10 месяцев назад

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

  • @phil86_
    @phil86_ 2 года назад

    Very interesting intro example

  • @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.

  • @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??

  • @puvididdle
    @puvididdle Год назад

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

  • @zbjz
    @zbjz 2 года назад

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

  • @Soulis98
    @Soulis98 2 года назад +2

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

  • @engineertrooper
    @engineertrooper Год назад

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

  • @inserteunnombreapropiado9079
    @inserteunnombreapropiado9079 9 месяцев назад

    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

  • @notoriousjdj
    @notoriousjdj 2 года назад +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).

  • @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.

  • @Nerpson
    @Nerpson 3 года назад +1

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

  • @cxl2377
    @cxl2377 2 года назад

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

  • @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?

  • @oihandeshayes6751
    @oihandeshayes6751 7 месяцев назад

    an update would be awesome

  • @mritunjaymusale
    @mritunjaymusale 2 года назад

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

  • @chrishabgood8900
    @chrishabgood8900 Год назад

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

  • @gabrielmengassodefranca1615
    @gabrielmengassodefranca1615 27 дней назад

    🔥🔥🔥🔥🔥🔥🔥🔥🔥

  • @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)

  • @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.

  • @blaises8221
    @blaises8221 5 месяцев назад

    what vs code extension are you using

  • @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

  • @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

  • @LukesOffline
    @LukesOffline 3 года назад +1

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

  • @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.

  • @callbettersaul
    @callbettersaul Год назад +1

    Isn't rng in that context Random Number Generator?

  • @__-_-__-_--_
    @__-_-__-_--_ 4 месяца назад

    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.

  • @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.

  • @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

  • @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 2 года назад +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!

  • @FaithOlusegun
    @FaithOlusegun Год назад

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

  • @tsdineshjai8565
    @tsdineshjai8565 2 месяца назад

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

  • @unknown-user001
    @unknown-user001 Год назад

    this is awesome for a lazy person like me.

  • @arkaprovobhattacharjee7044
    @arkaprovobhattacharjee7044 2 года назад

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

  • @Chuukwudi
    @Chuukwudi Месяц назад

    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.

  • @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 2 года назад

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

  • @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.

  • @jaykrown
    @jaykrown 5 месяцев назад

    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 5 месяцев назад

      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.

  • @skivar.
    @skivar. 2 года назад

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

  • @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.

  • @FM-xz4gz
    @FM-xz4gz 2 месяца назад +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);
    }

  • @cerealbowl7038
    @cerealbowl7038 3 месяца назад

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

  • @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"

  • @venkateswarans1012
    @venkateswarans1012 Год назад

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

  • @varad.h8
    @varad.h8 3 месяца назад

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

  • @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.

  • @Tom-JS
    @Tom-JS 11 месяцев назад

    Is rust readying for gui

  • @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!

  • @AngriestEwok
    @AngriestEwok 2 года назад

    For anyone following along and getting confused at 12:40 ish, color will not work on Windows consoles.

    • @lesleyrs
      @lesleyrs 2 года назад +2

      It does! Found the answer on the colored github.
      #[cfg(windows)]
      control::set_virtual_terminal(true).ok();

    • @AngriestEwok
      @AngriestEwok 2 года назад

      @@lesleyrs Oh that's neat. Thanks.

  • @johnvonhorn2942
    @johnvonhorn2942 10 месяцев назад

    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.

  • @marcosignoretto1150
    @marcosignoretto1150 Месяц назад

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

  • @erlangparasu6339
    @erlangparasu6339 2 года назад

    i dont understand, guest is i32, but return continue

  • @foobar1269
    @foobar1269 2 года назад +1

    gen_range(1..101);

  • @MrKB_SSJ2
    @MrKB_SSJ2 8 месяцев назад

    9:50

  • @matthijshebly
    @matthijshebly 5 месяцев назад +1

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

  • @greatjobbuddy
    @greatjobbuddy 2 года назад

    What is that gray text? It seems to give my code an error. I'm also using VS Code, but not having same experience.

    • @alwaysgood3913
      @alwaysgood3913 2 года назад +1

      It is part of the rust analyzer extension he uses, I have it too. It basically shows the default values set or any additional info as far as I know.

  • @moofymoo
    @moofymoo 2 года назад

    let mut guess = "abc";
    let guess = 42;
    🤯can redefine variables? what kind of black sorcery is this language?
    edit: oh, it's called shadowing, i felt that it has to do something with dark forces.

  • @kendlemintjed7571
    @kendlemintjed7571 Месяц назад

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

  • @quebirt
    @quebirt 2 месяца назад

    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.

  • @TwstedTV
    @TwstedTV Год назад

    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 🙃

  • @w___s
    @w___s 3 года назад +4

    It really sucks that you use this IDE that inserts extraneous annotations which break the code if carelessly duplicated in other editors. Very poor teaching decision.