我有一个由几个结构共享的Option<T>,它必须是可变的。我之所以使用RefCell,是因为据我所知,它是完成这项工作的工具。如何访问(和更改)该Option<T>的内容?
我尝试了以下几种方法:
use std::cell::RefCell;
#[derive(Debug)]
struct S {
val: i32
}
fn main() {
let rc: RefCell<Option<S>> = RefCell::new(Some(S{val: 0}));
if let Some(ref mut s2) = rc.borrow_mut() {
s2.val += 1;
}
println!("{:?}", rc);
}但是编译器不让我这么做:
error[E0308]: mismatched types
--> <anon>:10:12
|
10 | if let Some(ref mut s2) = rc.borrow_mut() {
| ^^^^^^^^^^^^^^^^ expected struct `std::cell::RefMut`, found enum `std::option::Option`
|
= note: expected type `std::cell::RefMut<'_, std::option::Option<S>, >`
found type `std::option::Option<_>`发布于 2017-07-12 17:42:11
正如编译器所说,当您对RefCell执行borrow_mut操作时,您会得到一个RefMut。要获得其中的值,只需使用运算符deref_mut
use std::cell::RefCell;
#[derive(Debug)]
struct S {
val: i32
}
fn main() {
let rc: RefCell<Option<S>> = RefCell::new(Some(S{val: 0}));
if let Some(ref mut s2) = *rc.borrow_mut() { // deref_mut
s2.val += 1;
}
println!("{:?}", rc);
}https://stackoverflow.com/questions/45053810
复制相似问题