首页 > 解决方案 > 为什么 read_line 不改变它的论点?

问题描述

fn main() {
    let mut input = String::new();

    loop {
        std::io::stdin()
            .read_line(&mut input)
            .expect("error: unable to read user input");

        println!("input is: {}", input);
    }
}

当我第一次输入hello时它会显示input is: hello,然后无论我以后输入什么它都会显示input is: hello,所以read_line不会改变input变量。为什么会这样?

标签: rust

解决方案


read_line确实改变了input变量,但它是通过附加到它而不是覆盖它来实现的。如果您想覆盖input,则应先将clear其传递给它,然后再将其传递给read_line它将为您提供所需的行为:

fn main() {
    let mut input = String::new();

    loop {
        input.clear(); // truncate string contents
        std::io::stdin()
            .read_line(&mut input)
            .expect("error: unable to read user input");

        println!("input is: {}", input);
    }
}

推荐阅读