(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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…