I have a trait, Out<T>
below, that I implement for a variety of types, including slice references.
I've aliased boxed dyn trait objects, and I'm curious about the lifetime specification.
My trait impl
for the slice ref doesn't require explicit lifetime declarations, I assume that the compiler and lifetime checker see that the reference only need to exist for the length of the function call. But when I make a trait object I need to specify a lifetime, here I use 'static
. Can someone explain the lifetime in this case? I realize that the type needs to life as long as the box, which can life as long as the program. But the call to the trait method, send
, does this lifetime need to bubble up into the owning struct?
I see that if I replace 'static
with 'a
and then add <'a>
to my struct and impl declarations this still compiles: Rust Playground
I guess I'm just trying to get a better understanding of the meaning of
dyn Out<&'static [i64]>
vs dyn Out<&'a [i64]>
pub trait Out<T> {
fn send(&self, value: T);
}
pub struct O;
type Outi64 = Box<dyn Out<i64>>;
type Outi64S = Box<dyn Out<&'static [i64]>>;
impl Out<i64> for O {
fn send(&self, _value: i64) {
// impl
}
}
impl Out<&[i64]> for O {
fn send(&self, _value: &[i64]) {
// impl
}
}
pub struct A {
o1: Outi64S,
o2: Outi64,
}
impl A {
pub fn new() -> Self {
Self {
o1: Box::new(O),
o2: Box::new(O),
}
}
}
Errors:
Compiling playground v0.0.1 (/playground)
warning: field is never read: `o1`
--> src/lib.rs:22:5
|
22 | o1: Outi64S,
| ^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: field is never read: `o2`
--> src/lib.rs:23:5
|
23 | o2: Outi64,
| ^^^^^^^^^^
warning: 2 warnings emitted
Finished dev [unoptimized + debuginfo] target(s) in 1.32s