2
votes
use std::any::Any;

pub enum ObjectType {
    Error,
    Function,
}

pub trait Object {
    fn obj_type(&self) -> ObjectType;

    // Required to downcast a Trait to specify structure
    fn as_any(&self) -> &dyn Any;
}

#[derive(Debug)]
pub struct Function<'a> {
    params: &'a Box<Vec<Box<String>>>,
}

impl<'a> Object for Function<'a> {
    fn obj_type(&self) -> ObjectType {
        ObjectType::Function
    }

    fn as_any(&self) -> &dyn Any { 
        self 
    }
}

When I try compiling the above code I get the following error. Here is the playground link to the code

Compiling playground v0.0.1 (/playground)
error[E0477]: the type `Function<'a>` does not fulfill the required lifetime
  --> src/lib.rs:27:9
   |
27 |         self 
   |         ^^^^
   |
   = note: type must satisfy the static lifetime

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/lib.rs:27:9
   |
27 |         self 
   |         ^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 21:7...
  --> src/lib.rs:21:7
   |
21 | impl <'a>Object for Function<'a> {
   |       ^^
note: ...so that the type `Function<'a>` will meet its required lifetime bounds
  --> src/lib.rs:27:9
   |
27 |         self 
   |         ^^^^
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
  --> src/lib.rs:27:9
   |
27 |         self 
   |         ^^^^
   = note: expected `&(dyn Any + 'static)`
              found `&dyn Any`

Why is Rust compiler getting confused about the struct lifetime, since I am just returning self. Also does it want the lifetime to be 'static. It's quite frustrating learning the language.

1

1 Answers

3
votes

The main issue is the as_any method defined in Function. If you look at the Any trait definition in the documentation, you will see that the trait has a lifetime bound of 'static. The params field in Function has a lifetime of 'a which won't live as long as a lifetime of 'static. One solution is to define the params field as a Box<Vec<Box<String>>>, instead of using a reference and defining a lifetime, but without further context, it is difficult to say.