传递RefCell的内容<& mut T>一个功能

时间:2018-04-15 12:21:58

标签: rust

对借来的RefCell<&mut T>(即Ref<&mut T>)调用方法按预期工作,但我似乎无法将其传递给函数。请考虑以下代码:

use std::cell::RefCell;

fn main() {
    let mut nums = vec![1, 2, 3];
    foo(&mut nums);
    println!("{:?}", nums);
}

fn foo(nums: &mut Vec<usize>) {
    let num_cell = RefCell::new(nums);

    num_cell.borrow_mut().push(4);

    push_5(*num_cell.borrow_mut());
}

fn push_5(nums: &mut Vec<usize>) {
    nums.push(4);
}

num_cell.borrow_mut().push(4)有效,但push_5(*num_cell.borrow_mut())错误:

error[E0389]: cannot borrow data mutably in a `&` reference
  --> src/main.rs:14:12
   |
14 |     push_5(*num_cell.borrow_mut());
   |            ^^^^^^^^^^^^^^^^^^^^^^ assignment into an immutable reference

在取消引用Ref之后,我希望在内部获得可变引用,因此错误对我来说并不合理。是什么给了什么?

1 个答案:

答案 0 :(得分:4)

  

push_5(*num_cell.borrow_mut());

删除*,编译器建议

error[E0308]: mismatched types
  --> src/main.rs:14:12
   |
14 |     push_5(num_cell.borrow_mut());
   |            ^^^^^^^^^^^^^^^^^^^^^
   |            |
   |            expected mutable reference, found struct `std::cell::RefMut`
   |            help: consider mutably borrowing here: `&mut num_cell.borrow_mut()`
   |
   = note: expected type `&mut std::vec::Vec<usize>`
              found type `std::cell::RefMut<'_, &mut std::vec::Vec<usize>>`

push_5(&mut num_cell.borrow_mut());编译。

push_5(num_cell.borrow_mut().as_mut());也是如此