I am trying to get a reference to the underlying struct from a trait object. I have looked at How to get a reference to a concrete type from a trait object?, the answers to which give insufficient details how to go about it. My question is mainly for a structure with lifetime annotations (or having references with lifetimes).
Below is my actual code
use std::any::Any;
trait Foo {
fn foo(&self) -> ();
fn as_any(&self) -> &dyn Any;
}
#[derive(Debug)]
struct S<'a> {
value: &'a str,
}
impl<'a> Foo for S<'a> {
fn foo(&self) -> () {}
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let s = "Hello World!";
let ss = S { value: s };
println!("{:?}", ss);
}
When I try to compile this, I get several errors related to lifetimes:
error[E0477]: the type `S<'a>` does not fulfill the required lifetime
--> src/main.rs:18:9
|
18 | self
| ^^^^
|
= note: type must satisfy the static lifetime
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:18:9
|
18 | self
| ^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 14:6...
--> src/main.rs:14:6
|
14 | impl<'a> Foo for S<'a> {
| ^^
note: ...so that the type `S<'a>` will meet its required lifetime bounds
--> src/main.rs:18:9
|
18 | self
| ^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/main.rs:18:9
|
18 | self
| ^^^^
= note: expected `&(dyn Any + 'static)`
found `&dyn Any`
Since the implementation of Any
requires the lifetime to be 'static
for the reference, is it not possible to implement the above implementation for structs with lifetime annotations? Is there a work-around?