Even though The Book is a bit verbose in these first few sections and really only touches on the basics of the language, I enjoyed going through it! Once you've gone to the end of just chapter 2, you've touched on project management with cargo
, compiling with rustc
or cargo
, match
statements, and some of the other syntactical details of the language. It's definitely enough to get you started if you're new to the language!
For me, my outstanding questions, which come from the final exercise that builds a "guessing game" (code extracted below for easy reference):
- Why are macros covered so much later in the book (ch 19)? ... not for mere mortals?
- I don't think I really know at all what an object like
Ordering
actually is and what mechanically happened when it was used in the match statement. - Why did I import/use
rand::Rng
but then writerand.thread_rng().gen_range()
. That I'm importing something not explicitly used in the code (Rng
is never used) feels off to me. I can only guess that this was a shortcut to get to use a higher level interface. But what isRng
? - This will probably come up when we cover "Ownership" ... but it strikes me now that we were passing variables by reference (eg
&secret_number
and&secret_number
. Given rust's concern with ownership and the "borrow checker" as a means of preventing memory safety issues ... why isn't it the default behaviour that a variable is passed by reference? Why do we have to explicitly pass the reference ourselves (with the ampersand syntax&secret_number
)?
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
// println!("Secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// let guess: u32 = guess.trim().parse().expect("Please type a number!");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("you guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win");
break;
}
}
}
}