在借用的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后,我希望在内部获得可变引用,因此该错误对我而言实际上没有任何意义。是什么赋予了?

最佳答案



删除*,编译器建议

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());也是

关于rust - 将RefCell <&mut T>的内容传递给函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49841847/

10-10 06:51