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.
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
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
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.
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); }
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.
"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.
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.
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??
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
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.
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.
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.
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.
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.
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.
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!
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
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
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 🙃
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).
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.
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
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.
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
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.
📝 Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet
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!
You are a God amongst humans! 🛐
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.
omg thank u so much
(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)
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);
Immuatable by default - that's pretty sweet
That part is familiar if you’re coming from F#, even down to the syntax.😊
Not sweet for Java C++ programmers tho. However, using it straight for a week gets your mind wrapped around the Rustic beauty.
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.
Yup is soo good
Don't forget to remove the line which prints the random number ;)
Complementing the book with this is really great. Thank you
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.
@@31redorange08 wasnt it because we redeclared guess as u32 and it just stayed that way?
or i just encountered a diff. situation
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
".
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
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
i like the idea of giving colour to the text, we don't normally do that
Finally i succes to find a good rust tutorial playlist.
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.
Thank you !!! Please keep up the good work
Match with Ordering looks genius. And that's only the beginning. I like this language already. Coming from TypeScript and Python world
Learning Rust while washing dishes. That is just great!
The poke lol. Imma steal that
Thanks for what you are doing brother. Peace & prosperity to your people.
nice explanation 🙌
Great material !
Keep doing it it helps a lot!
Thank you!
You're most welcome Erwin!
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);
}
thank you so much. great tutorial.
When i looked this up i didn't think it meant this rust
Isn't rng in that context Random Number Generator?
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.
"rng" isn't "range". It's "random number generator".
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.
excellent video! thank you!
you import rand::Rng and then use rand::thread_rng() how does that work?
"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.
amazing shit bro
me when i finish the game: le ruste developer
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.
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??
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
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
It's similar to C++ "using namespace std;"
Thank you sir , you have Awesome explanation for Rust. please keep up your work.
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.
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.
I installed the rust-analyser extension, but for some reason i have no linter nor help popups...
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.
gen_range(1..101);
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.
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.
God bless you, man. Instead of reading(&sleeping) I watch full aware and within 10mins chapters are completed.
haha the sign at the back looks like "lets get busty". thank you for the lesson.
@1:00 The author mentioned "language server". Can anyone elucidate, as I couldn't comprehend. Where do we have to install it ?
Hold up! This 'match' expression ... Is it like Switch statements as in other programming languages? I see match expression everywhere in rust.
you really shouldnt pronounce rng as range, since it stand for random number generation, it only leads to confusion
How do you get the extra info of i32, high, low, etc...?
Even if we type "quit", game just continues, what abt that? like we can't quit until we get the guess correct.
For those who are watching it from 2024, after stdin() and read_line the colon is no longer required to wrap a line
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.
Which plugin is used to display the docu snippets? Example: 1:56
Nice video :3
Short and limited to the interesting stuff.
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.
Hmm just wounder how rust allows to declare same variable named "guess" two times 😮
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!
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
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.
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
i learned alot from this it was a really jam packed video for me
The colors are not working. I am not getting any errors, but the text is still white.
what vs code extension are you using
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 🙃
I can't understand why but my loop block is not working.
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).
yes rust-analyzer
damn. you're giving more content in less time. you're amazing bro. thanks for teaching Rust
thanks for this video
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"
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
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!
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.
Is rust readying for gui
an update would be awesome
coming from the java background the ownership part is a little confusing.
What version of rust are you using? I have rustc and cargo 1.80.1. This won't compile.
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 ?
I haven't tried using keyboard shortcuts for cargo run. Did you configure that yourself?
@@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
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?
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.
Your channel really is the best Rust Language Channel. Thank you so much for all that you do.
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
The `continue' keyword doesn't really have any meaning outside of a loop
Watching this in August 2023 - good addition with colored. This is a great tutorial to follow along with the book - thanks!
Fantastic video!
What chair are you using?
What camera are you using?
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.
Hi! can you tell me the VS code extension that defines the commands ure using?
Yo I enjoy learning Rust because of your videos. The example you use, perfect...
Thank you so much for your videos man I like how you teach it's super clear for me!
4:41 for new viewers use "cargo add " in a terminal
this is awesome for a lazy person like me.
A M A Z I N G! I need more, hahaha. Great work buddy!
Am getting an error but my code is right can u help me
i dont understand, guest is i32, but return continue
🔥🔥🔥🔥🔥🔥🔥🔥🔥
simplifying things is a great skill. thanks
how do you get the run debug buttons to show up?
ur videos are great and perfect thanks :)
9:50
Thanks a lot! This is really helpful.
Wow, I just love this playlist !!
Very interesting intro example
Hi, what extension creates the gui that explains all the crate variables from rand?
Nevermind, installed the official rust extension and works fine now. (was using the alternative one)
Thanks!
Awesome video mate!
when I make a range 5:27 it doesn't come up with low and high
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.