修改后的 Rust 猜书游戏查询

Modified Rust Book Guessing Game Query

我修改了 Rust Book Guessing Game Tutorial 中的代码,使其更短一些;一张幻灯片。 las,我引入了一个错误,它不再正确执行:第一个输入按预期工作,但后续输入现在没有反馈。

防止这种情况的最佳方法是什么?

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, 101);

    let mut guess = String::new();

    loop {
        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");

        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;
            }
        }
    }
}

read_line 会将行附加到缓冲区,因此您的 guess 将累积所有包含换行符的输入!在循环内移动 let mut guess = String::new(); 解决了问题:

fn main() {
    ...

    loop {
        let mut guess = String::new();

        ...
    }
}