首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修改`RefCell<Option<T>>`的内容?

如何修改`RefCell<Option<T>>`的内容?
EN

Stack Overflow用户
提问于 2017-07-12 17:30:58
回答 1查看 2K关注 0票数 1

我有一个由几个结构共享的Option<T>,它必须是可变的。我之所以使用RefCell,是因为据我所知,它是完成这项工作的工具。如何访问(和更改)该Option<T>的内容?

我尝试了以下几种方法:

代码语言:javascript
复制
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);
}

但是编译器不让我这么做:

代码语言:javascript
复制
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<_>`
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-12 17:42:11

正如编译器所说,当您对RefCell执行borrow_mut操作时,您会得到一个RefMut。要获得其中的值,只需使用运算符deref_mut

代码语言:javascript
复制
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);
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45053810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档