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!
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.
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);
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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
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??
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.
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.
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""
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.
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
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
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
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); }
"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.
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.
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?
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".
@@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!
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; } }
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.
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.
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.
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).
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 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
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
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.