【发布时间】:2021-03-05 14:36:41
【问题描述】:
我正在尝试为具有内部可变性的结构实现 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 trait 我需要返回一个不可变的引用...
如果有任何关于如何处理这个问题的建议,我将不胜感激。
【问题讨论】:
标签: vector indexing rust immutability refcell