2

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user1244932
  • 7,352
  • 5
  • 46
  • 103

1 Answers1

1

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
evotopid
  • 5,288
  • 2
  • 26
  • 41
  • 1
    I do not want to use `'static` here, because of I don't see why I should do any restriction. If `Vec` can hold something, why should I not able to cast it to `Any`? – user1244932 Jun 01 '17 at 13:39
  • 3
    @user1244932 Check https://doc.rust-lang.org/std/any/trait.Any.html. The `'static` requirement comes from the `Any` trait. – kennytm Jun 01 '17 at 15:38
  • 2
    *it's a bit more complicated* — this is a bit of an understatement. It's simply not possible to use `Any` without static lifetimes at this point in time. – Shepmaster Jun 01 '17 at 20:58