The following code segment gives me an error:
use std::rc::Rc;
// Definition of Cat, Dog, and Animal (see the last code block)
// ...
type RcAnimal = Rc<Box<Animal>>;
fn new_rc_animal<T>(animal: T) -> RcAnimal
where
T: Animal /* + 'static */ // works fine if uncommented
{
Rc::new(Box::new(animal) as Box<Animal>)
}
fn main() {
let dog: RcAnimal = new_rc_animal(Dog);
let cat: RcAnimal = new_rc_animal(Cat);
let mut v: Vec<RcAnimal> = Vec::new();
v.push(cat.clone());
v.push(dog.clone());
for animal in v.iter() {
println!("{}", (**animal).make_sound());
}
}
error[E0310]: the parameter type `T` may not live long enough
--> src/main.rs:8:13
|
4 | fn new_rc_animal<T>(animal: T) -> RcAnimal
| - help: consider adding an explicit lifetime bound `T: 'static`...
...
8 | Rc::new(Box::new(animal) as Box<Animal>)
| ^^^^^^^^^^^^^^^^
|
note: ...so that the type `T` will meet its required lifetime bounds
--> src/main.rs:8:13
|
8 | Rc::new(Box::new(animal) as Box<Animal>)
| ^^^^^^^^^^^^^^^^
but this compiles fine:
use std::rc::Rc;
// Definition of Cat, Dog, and Animal (see the last code block)
// ...
fn new_rc_animal<T>(animal: T) -> Rc<Box<T>>
where
T: Animal,
{
Rc::new(Box::new(animal))
}
fn main() {
let dog = new_rc_animal(Dog);
let cat = new_rc_animal(Cat);
}
What is the cause of the error? The only real difference seems to be the use of operator as
. How can a type not live long enough? (playground)
// Definition of Cat, Dog, and Animal
trait Animal {
fn make_sound(&self) -> String;
}
struct Cat;
impl Animal for Cat {
fn make_sound(&self) -> String {
"meow".to_string()
}
}
struct Dog;
impl Animal for Dog {
fn make_sound(&self) -> String {
"woof".to_string()
}
}
Addendum
Just to clarify, I had two questions:
- Why doesn't this work? ... which is addressed in the accepted answer.
- How can a type, as opposed to a value or reference, be shortlived? ... which was addressed in the comments. Spoiler: a type simply exists since it's a compile-time concept.