The following code works the way expected, however I'm hoping to find a good reason why the "mut" qualifier is required on the first parameter when calling the add_employee fn.
Since the variable emps is defined with mut, and the signature expects it, why is that not sufficient?
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); } https://stackoverflow.com/questions/67248907/why-is-mut-required-for-fn-param-when-variable-defined-with-mut April 25, 2021 at 09:18AM
没有评论:
发表评论