繁体   English   中英

存储可变参考和生存期

[英]Storing mutable references and lifetimes

现在,我花了许多无用的时间来尝试使它起作用,但恐怕我现在唯一的办法就是尝试总结我的代码并向大家寻求帮助。

情况是,如果我在下面的代码中取消注释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]
    }
}

而是在Vec存储mut ref时发生的错误是:

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

如果有人可以解释为什么会发生,我会喜欢的。 从直观RefCellRefCell的借用超出范围似乎不应该成为问题。 Vec (因此RefCell太)不拥有该数据由基准指向,那么,为什么他们引用的寿命编译护理?

PS:我知道我的简化代码摘录并不清楚,为什么我要在Vec存储可变引用,或者为什么要使用RefCell这足以说明这不是偶然的

PPS我尝试在index方法和/或特征的关联类型上加上生命周期注释,但到目前为止,这样做只能获得不同的错误

它与不可变引用一起使用的原因是因为可以隐式复制那些引用。 当您切换为尝试返回&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

尽管上述所有内容都是正确的,但并不能真正解释为什么会收到特定的错误消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM