我想输入一个值,并将其赋给一个不可变的变量(应该是)。我该怎么做呢?
目前,我正在做这件事:
use std::io;
fn main() {
let mut a = 0;
let mut b = 1;
let mut nth_term = String::new();
io::stdin().read_line(&mut nth_term);
}但是如果没有&mut,它会生成一个错误:types differ in mutability。如果我从声明中删除mut,我会得到如下错误:
error[E0308]: mismatched types
--> src/main.rs:5:27
|
5 | io::stdin().read_line(&nth_term).expect("I/O error");
| ^^^^^^^^^ types differ in mutability
|
= note: expected mutable reference `&mut std::string::String`
found reference `&std::string::String`我怎么会有这样的东西:
let input_var = input(); // or some other function that inputs the value and directly assigns it.我尝试了reading the official documentation, the first few chapters,,但徒劳无功。
发布于 2020-02-16 00:00:36
Rust中的可变性跟在名称后面,而不是值后面。因此,如果你有一个绑定到可变变量的值,并且你希望它是不可变的,那么你所要做的就是重新绑定它:
fn main() {
let mut nth_term = String::new();
io::stdin().read_line(&mut nth_term).expect("I/O error");
let nth_term = nth_term;
// ^^^^^^^^-- no `mut`
}将值重新绑定到具有不同可变性的相同名称是很常见的(请参阅What does 'let x = x' do in Rust?)。
还可以将原始绑定放在块表达式中,以最小化mut变量的作用域:
fn main() {
let nth_term = {
let mut nth_term = String::new();
io::stdin().read_line(&mut nth_term).expect("I/O error");
nth_term
};
}BufRead::read_line是这样定义的,这样您就不需要为每个新行读取分配一个新的String。该方法必须接受&mut,因为它可以增长字符串。尽管您可以使用stdin().lines()迭代输入行,但没有标准I/O函数可以从标准输入中读取一行并返回String (您可以简单地将其绑定到非mut变量)。当然,如果您发现自己经常这样做,您可以编写自己的函数,该函数包含mut并返回,例如,一个io::Result<String>。
https://stackoverflow.com/questions/60240195
复制相似问题