1
struct Wrap<'a> {
    pub data: Option<&'a i32>,
}

pub trait Boxable {
    fn get_data(&self) -> Option<&i32>;
}

impl<'a> Boxable for Wrap<'a> {
    fn get_data(&self) -> Option<&i32> {
        self.data
    }
}

struct ContTrait {
    pub vbox: Box<Boxable>,
}

struct ContWrap<'a> {
    pub vbox: Box<Wrap<'a>>,
}

fn main() {
    let x1 = 15;

    let bt = Box::new(Wrap { data: Some(&x1) });
    // let mut c = ContTrait { vbox: Box::new(Wrap {data : Some(&x1)}) };
    let mut c2 = ContWrap {
        vbox: Box::new(Wrap { data: Some(&x1) }),
    };
}

I can't justify why only the commented line can't be compiled and thinks x1's lifetime is not long enough. It seems c2 is equivalent to it, except the Box is for the Wrap struct directly. bt just removes one layer of struct. I can't figure out what makes ContTrait behave so differently.

Here's the error message when uncommenting the ContTrait line:

error[E0597]: `x1` does not live long enough
  --> src/main.rs:27:63
   |
27 |     let mut c = ContTrait { vbox: Box::new(Wrap {data : Some(&x1)}) };
   |                                                               ^^ borrowed value does not live long enough
...
31 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

playground

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • `Box` is equivalent to `Box`. If you want some other lifetime, you need to be explicit and use `Box`. – Sven Marnach Dec 13 '18 at 13:03
  • (Not sure whether this qualifies as a duplicate, but the answer covers the important points to note here.) – Sven Marnach Dec 13 '18 at 13:13
  • Based on your error messages, you are still using Rust 2015. You are encouraged to [switch to Rust 2018](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html), which provides a better error message here. – Shepmaster Dec 13 '18 at 23:20

0 Answers0