小编Mar*_*rik的帖子

如何返回一个引用了 RefCell 内部内容的迭代器?

我试图创建一个方法,它返回了值的迭代器HashMap是内部的盒装RefCell,但我在那里的错误Ref被退回RefCell::borrow 不足够长寿的迭代器从该方法返回。这是我的代码:

use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_map::Values;

struct Foo {
    map: Rc<RefCell<HashMap<i32, i32>>>,
}

impl Foo {
    fn iter(&self) -> Values<i32, i32> {
        self.map.borrow().values()
    }
}

fn main() {
    let foo = Foo {
        map: Rc::new(RefCell::new(HashMap::new()))
    };

    for v in foo.iter() {
        println!("{}", v)
    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::hash_map::Values;

struct Foo {
    map: Rc<RefCell<HashMap<i32, i32>>>,
}

impl Foo {
    fn iter(&self) -> Values<i32, i32> …
Run Code Online (Sandbox Code Playgroud)

iterator reference rust interior-mutability

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

标签 统计

interior-mutability ×1

iterator ×1

reference ×1

rust ×1