2
votes

I want to work with several Vec at once. These vectors can be specialized with different types. I created a trait:

trait Column {
    //fn insert
    //fn remove
}

impl<T> Column for Vec<T> // ...

I can convert Vec<T1> and Vec<T2> to Box<Column>, but I also need to convert Box<Column> back to Vec. As suggested in How to get a struct reference from a boxed trait?, I wrote:

use std::any::Any;

trait Column {
    fn as_any(&self) -> &Any;
}

impl<T> Column for Vec<T>
    where T: Default
{
    fn as_any(&self) -> &Any {
        self //ERROR!
    }
}

but this code generates an error:

error[E0310]: the parameter type `T` may not live long enough
  --> src/main.rs:11:9
   |
11 |         self //ERROR!
   |         ^^^^
   |
   = help: consider adding an explicit lifetime bound `T: 'static`...
note: ...so that the type `std::vec::Vec<T>` will meet its required lifetime bounds
  --> src/main.rs:11:9
   |
11 |         self //ERROR!
   |         ^^^^

How can I fix this issue?

1
Can you include more of the compiler's output? What lines have triggered the error? - E_net4 the curator
@E_net4 I updated my question, the error triggered by the sole line of code. - user1244932

1 Answers

1
votes

The easiest way is to add the 'static constraint to T, i.e.

impl<T> Column for Vec<T>
    where T: Default + 'static
{
    fn as_any(&self) -> &Any {
        self
    }
}

This means that if T has any lifetime parameters they have to be 'static. If you want to also make it work for types with lifetime parameters, it's a bit more complicated. (I'm not sure how that would work.)

By the way, the Rust compiler sometimes provides suggestions like this so reading the error messages is really useful. You can also run rustc --explain E0310 (or whatever error code it is) and maybe the explanation is enough to figure out the solution.