Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "explicit lifetime bound required" for Box<T> in struct?

Tags:

Editor's note: This code no longer produces the same error after RFC 599 was implemented, but the concepts discussed in the answers are still valid.

I'm trying to compile this code:

trait A {     fn f(&self); }  struct S {     a: Box<A>, } 

and I'm getting this error:

a.rs:6:13: 6:14 error: explicit lifetime bound required a.rs:6     a: Box<A>, 

I want S.a to own an instance of A, and don't see how that lifetime is appropriate here. What do I need to do to make the compiler happy?

My Rust version:

rustc --version rustc 0.12.0-pre-nightly (79a5448f4 2014-09-13 20:36:02 +0000) 
like image 307
Eugene Zemtsov Avatar asked Sep 21 '14 12:09

Eugene Zemtsov


1 Answers

(Slightly pedantic point: that A is a trait, so S is not owning an instance of A, it is owning an boxed instance of some type that implements A.)

A trait object represents data with some unknown type, that is, the only thing known about the data is that it implements the trait A. Because the type is not known, the compiler cannot directly reason about the lifetime of the contained data, and so requires that this information is explicitly stated in the trait object type.

This is done via Trait+'lifetime. The easiest route is to just use 'static, that is, completely disallow storing data that can become invalid due to scopes:

a: Box<A + 'static> 

Previously, (before the possibility of lifetime-bounded trait objects and this explicit lifetime bound required error message was introduced) all boxed trait objects were implicitly 'static, that is, this restricted form was the only choice.

The most flexible form is exposing the lifetime externally:

struct S<'x> {     a: Box<A + 'x> } 

This allows S to store a trait object of any type that implements A, possibly with some restrictions on the scopes in which the S is valid (i.e. for types for which 'x is less than 'static the S object will be trapped within some stack frame).

like image 194
huon Avatar answered Oct 31 '22 12:10

huon