我有一个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);
}
Run Code Online (Sandbox Code Playgroud)
但编译器不会让我这样做:
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<_>`
Run Code Online (Sandbox Code Playgroud)
当你borrow_mut的RefCell,你得到了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);
}
Run Code Online (Sandbox Code Playgroud)