1

我正在尝试为具有内部可变性的结构实现 Index 方法:

pub struct FooVec {
    foo: RefCell<Vec<i32>>
}

impl Index<usize> for FooVec {
    type Output = i32;

    fn index(&self, index: usize) -> &Self::Output {
        self.foo.borrow().index(index)
    }
}

但是,由于以下原因无法编译:

error[E0515]: cannot return value referencing temporary value
 --> src\lacc\expr.rs:9:9
  |
9 |         self.foo.borrow().index(index)
  |         -----------------^^^^^^^^^^^^^
  |         |
  |         returns a value referencing data owned by the current function
  |         temporary value created here

我的解决方案是在 RefCell 中返回向量的引用。但是我找到的唯一方法是 get_mut() 并且对于 Index 特征,我需要返回一个不可变的引用......

我将不胜感激有关如何处理此问题的任何建议。

4

1 回答 1

3

你不能实现IndexIndex特征需要返回一个引用,这意味着它必须返回一些附加到对象并且可以从对象中轻松访问的东西。

这里不是这种情况,因为您需要通过RefCell::borrow,它的功能本质上就像是从头开始创建一个值(因为它只通过Ref "lock guard" 分发访问权限)。

我将不胜感激有关如何处理此问题的任何建议。

做点别的。Index不是一种选择。考虑到所涉及的类型,我建议只实现一个get返回 an 的方法Option<i32>,类似的东西。

于 2021-03-05T14:54:10.610 回答