rust - 为什么 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
变量。为什么会这样?
解决方案
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);
}
}
推荐阅读
- r - 如何过滤列中包含少于 3 个空格的行?(右)
- python - 将字符串列表转换为唯一的 rgb 颜色
- visual-studio-code - VS Code 一段时间后自行重启 PC
- reactjs - 创建选择组件并希望将事件方法传递出去
- reactjs - 防止范围滑块处理程序相互交叉(material-ui/reactjs)
- java - 使用java在数据库中导入Excel文件
- thymeleaf - 如何设置模板路径
- javascript - 如何使 Handsontable 可用于我的 Laravel Blade 组件?
- android - 计费库 - 测试不同国家/地区的 InApp 订阅
- laravel - Laravel 关系搜索