loop and break

This commit is contained in:
2022-12-13 08:59:43 -05:00
parent 7cbfe8dbc9
commit ddd68240e7

View File

@ -17,26 +17,33 @@ fn main() {
let mut guess = String::new(); let mut guess = String::new();
// could still call this without importing it via std::io::stdin // could still call this without importing it via std::io::stdin
// this can be one line, it is broken up for readability. // this can be one line, it is broken up for readability.
io::stdin() loop {
// & indicates that this argument is a reference, io::stdin()
// references are also immutable by default so &mut is needed // & indicates that this argument is a reference,
.read_line(&mut guess) // references are also immutable by default so &mut is needed
// expect handles the Err variant by crashing the program. There are other ways to handle .read_line(&mut guess)
// errors. // expect handles the Err variant by crashing the program. There are other ways to handle
.expect("Failed to read line"); // errors.
// read_line returns a `result` value. result is an enum. Each possible state is a variant. .expect("Failed to read line");
// Result's variants are Ok and Err // read_line returns a `result` value. result is an enum. Each possible state is a variant.
// Result's variants are Ok and Err
// shadowing V // shadowing V
let guess: u32 = guess.trim().parse().expect("please type a number for the love of god"); let guess: u32 = guess.trim().parse().expect("please type a number for the love of god");
// trim removes space and \n // trim removes space and \n
println!("you guessed: {guess}"); // single colon is type annotation
// a match expression is made of arms. an arm is a pattern to match and code to run against it. //
// switch/case println!("you guessed: {guess}");
match guess.cmp(&secret_number) { // a match expression is made of arms. an arm is a pattern to match and code to run against it.
Ordering::Less => println!("too small"), // switch/case
Ordering::Greater => println!("too big"), match guess.cmp(&secret_number) {
Ordering::Equal => println!("you win"), Ordering::Less => println!("too small"),
Ordering::Greater => println!("too big"),
Ordering::Equal => {
println!("you win");
break;
}
}
} }
} }
// cargo doc --open // cargo doc --open