【问题标题】:Borrowing a borrowed mutable type借用一个借来的可变类型
【发布时间】:2020-10-19 01:01:59
【问题描述】:

具有借用可变引用的函数如何调用具有相同借用可变引用的第二个函数?

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中代码的链接

【问题讨论】:

    标签: rust


    【解决方案1】:

    通过编写&amp;mut a,您是在尝试对a 进行可变引用,而不是对其值引用的内容——它将是&amp;mut &amp;mut Vec&lt;i32&gt;a 的值已经是你想要的可变引用了:

    second_function(a);
    

    updated playground

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2016-07-22
      相关资源
      最近更新 更多