具有借用的可变引用的函数如何调用具有相同借用的可变引用的第二个函数?
fn main() {
let mut a = vec![0, 1, 2, 3, 4];
first_function(&mut a);
println!("{:?}", a);
}
fn first_function(a: &mut Vec<i32>) {
println!("...first function");
a[0] = 5;
second_function(&mut a);
}
fn second_function(a: &mut Vec<i32>) {
println!("...second function");
a[2] = 6;
}编译器错误通常非常有用,但我不理解这个错误;
error[E0596]: cannot borrow `a` as mutable, as it is not declared as mutable
--> src/main.rs:12:21
|
9 | fn first_function(a: &mut Vec<i32>) {
| - help: consider changing this to be mutable: `mut a`
...
12 | second_function(&mut a);
| ^^^^^^ cannot borrow as mutable..。以下是指向Rust Playground中代码的链接
发布于 2020-06-29 05:30:54
通过编写&mut a,您试图接受对a的可变引用,而不是它的值引用的内容-它将是一个&mut &mut Vec<i32>。a的值已经是你想要的可变引用:
second_function(a);https://stackoverflow.com/questions/62628414
复制相似问题