[英]Rust Rc<RefCell>::borrow_mut returns &mut Rc<RefCell<T>> instead of RefMut<T>
so I'm relatively new in Rust and I was trying to get something similair to a std::shared_ptr in C++. I decided to go with the Rc<RefCell> pattern.所以我在 Rust 中相对较新,我试图在 C++ 中获得与 std::shared_ptr 类似的东西。我决定使用 Rc<RefCell> 模式的 go。
I'm trying to get and modify the value of Rc<RefCell<i32>>
but borrow_mut()
keeps returning &mut Rc<RefCell<i32>>
instead of MutRef<i32>
我正在尝试获取和修改
Rc<RefCell<i32>>
的值,但borrow_mut()
一直返回&mut Rc<RefCell<i32>>
而不是MutRef<i32>
I'm working on 2 projects currently.我目前正在从事 2 个项目。 In the first project
test_mut
is of type RefMut<i32>
.在第一个项目中,
test_mut
的类型是RefMut<i32>
。
let mut test: Rc<RefCell<i32>> = Rc::new(RefCell::new(5));
let test_mut = test.borrow_mut();
But in my other project test_mut
is of type &mut Rc<RefCell<i32>>
.但是在我的其他项目中,
test_mut
的类型是&mut Rc<RefCell<i32>>
。
WHYYY??为什么??
When I don't let the compiler deduct the type and replace the code with:当我不让编译器扣除类型并将代码替换为:
let mut test: Rc<RefCell<i32>> = Rc::new(RefCell::new(5));
let test_mut: RefMut<i32> = test.borrow_mut();
I get the following error:我收到以下错误:
mismatched types
expected struct `RefMut<'_, i32>`
found mutable reference `&mut Rc<RefCell<i32>>`
If anyone has any idea how I can prevent this, you would be my hero:)如果有人知道我如何防止这种情况发生,你就是我的英雄:)
Locke's comment is right.洛克的评论是正确的。
Because of the method resolution rules , if you have use std::borrow::BorrowMut;
由于方法解析规则,如果你
use std::borrow::BorrowMut;
, BorrowMut::borrow_mut
will get called instead of RefCell::borrow_mut
. ,
BorrowMut::borrow_mut
将被调用而不是RefCell::borrow_mut
。 Basically, trait methods on the current type ( &mut RefCell
) are checked before methods on the deref type ( &Rc
).基本上,当前类型 (
&mut RefCell
) 的特征方法在 deref 类型 ( &Rc
) 的方法之前被检查。
You can either remove the import, or call it as an associated function:您可以删除导入,或将其作为关联的 function 调用:
let test_mut = RefCell::borrow_mut(&test);
This isn't necessary here, but the equivalent code without automatic deref would be:这在这里不是必需的,但是没有自动取消引用的等效代码是:
use std::ops::Deref;
let test_mut = RefCell::borrow_mut(Deref::deref(&test))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.