【问题标题】:Passing the contents of a RefCell<&mut T> to a function将 RefCell<&mut T> 的内容传递给函数
【发布时间】:2018-04-15 12:21:58
【问题描述】:

在借来的RefCell&lt;&amp;mut T&gt;(即Ref&lt;&amp;mut T&gt;)上调用方法按预期工作,但我似乎无法将它传递给函数。考虑以下代码:

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 之后,我希望在里面得到可变引用,所以这个错误对我来说真的没有意义。什么给了?

【问题讨论】:

    标签: rust


    【解决方案1】:

    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(&amp;mut num_cell.borrow_mut()); 编译。

    push_5(num_cell.borrow_mut().as_mut()); 也可以

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-20
      • 2020-05-26
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多