1

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
gabhijit
  • 3,345
  • 2
  • 23
  • 36
  • It looks like your question might be answered by the answers of [Lifetime issue with the Any trait](https://stackoverflow.com/q/54503120/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Dec 22 '20 at 16:37
  • TL;DR, from the [docs](https://doc.rust-lang.org/std/any/), emphasis mine: *the `Any` trait, which enables dynamic typing of **any `'static` type***. – Shepmaster Dec 22 '20 at 16:37
  • 1
    Yes that answer already answers this question. Thanks – gabhijit Dec 23 '20 at 05:05

0 Answers0