相关疑难解决方法(0)

如何在不破坏封装的情况下返回对RefCell内部内容的引用?

我有一个内部可变性的结构.

use std::cell::RefCell;

struct MutableInterior {
    hide_me: i32,
    vec: Vec<i32>,
}
struct Foo {
    //although not used in this particular snippet,
    //the motivating problem uses interior mutability
    //via RefCell.
    interior: RefCell<MutableInterior>,
}

impl Foo {
    pub fn get_items(&self) -> &Vec<i32> {
        &self.interior.borrow().vec
    }
}

fn main() {
    let f = Foo {
        interior: RefCell::new(MutableInterior {
            vec: Vec::new(),
            hide_me: 2,
        }),
    };
    let borrowed_f = &f;
    let items = borrowed_f.get_items();
}
Run Code Online (Sandbox Code Playgroud)

产生错误:

error[E0597]: borrowed value does not live long enough
  --> …
Run Code Online (Sandbox Code Playgroud)

encapsulation contravariance mutability rust interior-mutability

21
推荐指数
3
解决办法
2487
查看次数

从 Rust 中的 RefCell&lt;Option&lt;Rc&lt;T&gt;&gt;&gt; 获取引用

我在从 RefCell<Option<Rc>> 获取引用时遇到问题。

有什么建议吗?

struct Node<T> {
    value: T
}

struct Consumer3<T> {
    tail: RefCell<Option<Rc<Node<T>>>>,
}

impl<T> Consumer3<T> {
    fn read<'s>(&'s self) -> Ref<Option<T>> {
        Ref::map(self.tail.borrow(), |f| {
            f.map(|s| {
                let v = s.as_ref();
                v.value
            })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

给出:

struct Node<T> {
    value: T
}

struct Consumer3<T> {
    tail: RefCell<Option<Rc<Node<T>>>>,
}

impl<T> Consumer3<T> {
    fn read<'s>(&'s self) -> Ref<Option<T>> {
        Ref::map(self.tail.borrow(), |f| {
            f.map(|s| {
                let v = s.as_ref();
                v.value
            })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

rust

1
推荐指数
1
解决办法
754
查看次数