以下代码段给我一个错误:
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>)
| ^^^^^^^^^^^^^^^^
但这编译得很好:
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);
}
错误的原因是什么?唯一真正的区别似乎是运算符的使用as
。怎样才能一个type活得不够长? ()
// 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
只是为了澄清,我有两个问题:
- 为什么这不起作用? ...这在已接受的答案中得到了解决。
- 怎样才能一个type,而不是价值或参考,是短暂的吗? ...这在评论中得到了解决。剧透:type简单地存在,因为它是一个编译时概念。