2017-07-26 70 views
3

下面的代碼無法編譯:壽命的參考值盒裝不活足夠長的時間

use std::borrow::Borrow; 

struct Inner<'a> { 
    v: Vec<&'a u8>, 
} 

struct Foo<'a> { 
    inner: Inner<'a>, 
    derp: Box<u8>, 
} 

impl<'a> Foo<'a> { 
    fn new() -> Foo<'a> { 
     let mut e = Foo { 
      inner: Inner { v: vec![] }, 
      derp: Box::new(128), 
     }; 
     e.inner.v.push(&*e.derp); 

     return e; 
    } 

    fn derp(&mut self) { 
     println!("{:?}", self.inner.v); 
    } 
} 

fn main() { 
    let mut f = Foo::new(); 

    f.derp(); 
} 

我得到以下錯誤:

error[E0597]: `*e.derp` does not live long enough 
    --> src/main.rs:18:25 
    | 
18 |   e.inner.v.push(&*e.derp); 
    |       ^^^^^^^ does not live long enough 
... 
21 |  } 
    |  - borrowed value only lives until here 
    | 
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 12:1... 
    --> src/main.rs:12:1 
    | 
12 |/impl<'a> Foo<'a> { 
13 | |  fn new() -> Foo<'a> { 
14 | |   let mut e = Foo { 
15 | |    inner: Inner { v: vec![] }, 
... | 
25 | |  } 
26 | | } 
    | |_^ 

我覺得那裏面的值了盒子的壽命只有'a,因爲它是Foo的成員,它具有這樣的壽命。

我想知道在新函數結束時Foo的移動是否令人困惑,因此如果試圖在derp中執行附加操作。我得到了一個不同的錯誤:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements 
    --> main.rs:20:27 
    | 
20 |   self.inner.v.push(& *self.derp); 
    |       ^^^^^^^^^^ 

這給我沒有跡象表明編譯器認爲盒裝值有多長。

回答

3

I think though that the value inside of the box does live for as long as 'a since it is a member of Foo which has exactly that lifetime.

它可以在它結束分配一個新的方框,derp構件,在該點處的老框將被丟棄,並且該值的壽命。

我認爲你正在嘗試做的事情是不可能的在安全鏽:不支持結構成員之間的交叉引用。這經常作爲一個問題出現,但它只是在語言中不可用。

您可以使用Rc來解決這個問題,也許結合RefCell

+0

啊,我明白了。我想這是有道理的。我想知道是否有任何方法可以阻止這種可能性,並迫使這個盒子在'一個人的整個生命中生活。 –