Box lifetime problem

Why compiler say :

error: `game` does not live long enough
 --> src\main.rs:4:62
  |
4 |     let card = Card { feature : Box::new(ColorFeature { g : &game})};
  |                                                              ^^^^ does not live long enough
5 | }
  | - borrowed value only lives until here
  |
  = note: borrowed value must be valid for the static lifetime...

Code is below:

fn main() {
	let game = Game { };
	let card = Card { feature : Box::new(ColorFeature { g : &game})};
}

struct Card {
	feature : Box<Feature>
}

trait Feature {

}

struct ColorFeature<'a> {
	g : &'a Game
}

impl<'a> Feature for ColorFeature<'a> {

}

struct Game {

}

By default Box implies 'static lifetime. You need

struct Card<'a> {
    feature : Box<Feature + 'a>
}
10 Likes

Thank you very much.

what is meaning of Feature+'a

Feature by itself is a trait. When it used by itself in contexts like Box<Feature> or &Feature it denotes a special type: trait object.

That is, Box<Feature> is some opaque type behind a pointer, which implements the Feature trait. Because this type is opaque, it can contain references and may depend on some lifetime. By default, Rust assumes that this lifetime is 'static (i.e. that there's no references). That is Box<Feature> is a shorthand for Box<Feature + 'static>.

But in this particular case there is a &'a reference, so we need to write Feature + 'a.

1 Like