存储可变引用和生命周期

时间:2015-02-16 23:45:52

标签: rust lifetime borrow-checker

我现在花了很多时间试图让这个工作起作用,但我担心我现在唯一的办法是尝试总结我的代码并请求大家帮忙。

情况是,如果我在以下代码中取消注释mut的两个实例,它将不再编译(并且不是出于对我有意义的原因):

use std::cell::RefCell;
use std::ops::Index;

struct Foo<'a, T: 'a> {
    t_array: [T; 3],
    t_refs: RefCell<Vec<&'a /* mut */ T>>, //'           // 1
}
impl<'a, T> Foo<'a, T> {
    fn new(t1: T, t2: T, t3: T) -> Foo<'a, T> { //'
        Foo {
            t_array: [t1, t2, t3],
            t_refs: RefCell::new(Vec::with_capacity(3))
        }
    }
    fn add_t_ref(&'a mut self, at_index: usize) { //'
        let t_ref = & /* mut */ self.t_array[at_index];  // 2
        let mut t_refs = self.t_refs.borrow_mut();
        t_refs.push(t_ref);
    }
}
impl<'a, T> Index<usize> for Foo<'a, T> {
    type Output = T;
    #[inline]
    fn index(&self, index: &usize) -> &T {
        let t_refs = self.t_refs.borrow();
        t_refs[*index]
    }
}

mut中存储Vec引用时发生的错误是:

blah3_mut.rs:26:9: 26:15 error: `t_refs` does not live long enough
blah3_mut.rs:26         t_refs[*index]
                        ^~~~~~
blah3_mut.rs:24:42: 27:6 note: reference must be valid for the anonymous lifetime #1 defined on the block at 24:41...
blah3_mut.rs:25:42: 27:6 note: ...but borrowed value is only valid for the block suffix following statement 0 at 25:41

如果有人能解释为什么会这样,我会很高兴;从直觉上看,RefCell的借用超出范围似乎不应成为问题。 Vec(以及RefCell)也不拥有引用指向的数据,那么编译器为什么要关心 引用的生命周期?

P.S。我知道我的简化代码摘录并不能说明为什么我在Vec中存储可变引用或为什么我使用RefCell - 这足以说明它不是偶然的

P.P.S。我尝试在index方法和/或特征的相关类型上使用生命周期注释进行一些处理,但到目前为止只能设法得到不同的错误

1 个答案:

答案 0 :(得分:2)

它与不可变引用一起使用的原因是因为可以隐式复制它们。当您切换到尝试返回&mut时,会有两个地方有该引用 - Vec和您的函数的调用者。这将引入别名,并且Rust中不允许使用可变别名。

您甚至可以忽略Index实施,只需尝试此操作:

fn main() {
    let mut f = Foo::new(1,2,3);
    f.add_t_ref(1);
    f.add_t_ref(2);
}

你会得到:

error: cannot borrow `f` as mutable more than once at a time

虽然上述所有情况都属实,但它并没有真正解释您收到特定错误消息的原因。

相关问题