[edit: This was originally a reply to this old thread. —@mbrubeck]
I'm a complete beginner who is learning through the Book. Does it make sense to rewrite (just for learning) Listing 2-1 like this?
use std::io::{self, BufRead};
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let guess = io::stdin()
.lock()
.lines()
.next()
.expect("Failed to read line")
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
Yes, that's a reasonable equivalent to the original code from the book.
2 Likes
Thanks!
At the end of chapter 2 I've got this code (equivalent of Listing 2-6):
use rand::Rng;
use std::cmp::Ordering;
use std::io::{self, BufRead};
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let guess = match io::stdin().lock().lines().next() {
Some(Ok(line)) => line,
Some(Err(err)) => panic!("Failed to read line: {:?}", err),
None => continue,
};
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;
},
}
}
}
system
closed
#5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.