下面的代码以预期的方式工作,但是我希望找到一个很好的理由,为什么在调用add_employee fn时第一个参数需要"mut“限定符。
既然变量emps是用mut定义的,而签名需要它,为什么这还不够呢?
struct Employee {
name: String,
age: u16,
}
impl Employee {
fn new() -> Employee {
Employee {
name: "Julia".to_string(),
age: 15
}
}
}
fn add_employee(emps: &mut Vec<Employee>, emp: Employee) {
emps.push(emp);
}
fn main() {
let mut emps: Vec<Employee> = Vec::new();
add_employee(&mut emps, Employee::new()); // why is mut required here?
println!("name = {}, age = {}", emps[0].name, emps[0].age);
}发布于 2021-04-25 09:59:47
因为可变性是variables和references的属性,而不是它们引用的数据。在没有函数调用的情况下,这一点更容易看到。
// emps is a mutable variable.
let mut emps: Vec<Employee> = Vec::new();
// this is fine, emps is being mutated.
emps.push(Employee { name: "First".to_string(), age: 42 });
// emps_ref is an immutable variable containing an immutable reference.
let emps_ref = &emps;
// this is an error, push() cannot mutate an immutable reference.
emps_ref.push(Employee { name: "Second".to_string(), age: 99 });相反,为了改变引用,我们需要一个可变引用:let emps_ref = &mut emps。类似地,传递到add_employee的引用必须是可变的。
注意,emps_ref变量是不可变的,不能再次赋值给它。
https://stackoverflow.com/questions/67248907
复制相似问题