相关疑难解决方法(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
查看次数

如何借用RefCell <HashMap>,找到一个键,并返回对结果的引用?

我有一个RefCell<HashMap>并想借用表,找到一个键,并返回对结果的引用:

use std::cell::RefCell;
use std::collections::HashMap;

struct Frame {
    map: RefCell<HashMap<String, String>>,
}

impl Frame {
    fn new() -> Frame {
        Frame {
            map: RefCell::new(HashMap::new()),
        }
    }

    fn lookup<'a>(&'a self, k: &String) -> Option<&'a String> {
        self.map.borrow().get(k)
    }
}

fn main() {
    let f = Frame::new();
    println!("{}", f.lookup(&"hello".to_string()).expect("blargh!"));
}
Run Code Online (Sandbox Code Playgroud)

(游乐场)

如果我删除RefCell然后一切正常:

struct Frame {
    map: HashMap<String, String>,
}

impl Frame {
    fn lookup<'a>(&'a self, k: &String) -> Option<&'a String> {
        self.map.get(k)
    }
}
Run Code Online (Sandbox Code Playgroud)

在不复制哈希表中的字符串的情况下编写查找函数的正确方法是什么?

rust interior-mutability

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