首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mut定义变量时,fn参数为什么需要mut

使用mut定义变量时,fn参数为什么需要mut
EN

Stack Overflow用户
提问于 2021-04-25 09:18:44
回答 1查看 26关注 0票数 1

下面的代码以预期的方式工作,但是我希望找到一个很好的理由,为什么在调用add_employee fn时第一个参数需要"mut“限定符。

既然变量emps是用mut定义的,而签名需要它,为什么这还不够呢?

代码语言:javascript
复制
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);
}
EN

回答 1

Stack Overflow用户

发布于 2021-04-25 09:59:47

因为可变性是variablesreferences的属性,而不是它们引用的数据。在没有函数调用的情况下,这一点更容易看到。

代码语言:javascript
复制
// 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变量是不可变的,不能再次赋值给它。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67248907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档