我正试图让我的脑袋围绕着仿制药和生命周期互动的方式。考虑:
use std::ops::Add;
struct Gloop<'a, T: Add> {
wumpus: &'a Wumpus<T>,
}
trait Wumpus<T: Add> {
fn fleeb(&self, x: &T) -> bool;
}
struct Mimsy {
jubjub: f64,
}
impl<T: Add> Wumpus<T> for Mimsy {
fn fleeb(&self, x: &T) -> bool {
return (x + x) > 0;
}
}
fn main() {
let a = Mimsy { jubjub: 1. };
let b = Gloop::<i32> { wumpus: &a };
println!("{}", b.fleeb(1));
}
哪个收益率:
error[E0309]: the parameter type `T` may not live long enough
--> src/main.rs:4:5
|
3 | struct Gloop<'a, T: Add> {
| -- help: consider adding an explicit lifetime bound `T: 'a`...
4 | wumpus: &'a Wumpus<T>,
| ^^^^^^^^^^^^^^^^^^^^^
|
note: ...so that the reference type `&'a Wumpus<T> + 'a` does not outlive the data it points at
--> src/main.rs:4:5
|
4 | wumpus: &'a Wumpus<T>,
| ^^^^^^^^^^^^^^^^^^^^^
我的程序中哪个对象可能活得不够长? Gloop
或Mimsy
(或任何Wumpus<T>
)中的任何地方都无法存储T
。
答案 0 :(得分:0)
注意:我回答了这个问题,但认为问题实际上是
的重复"The parameter type `C` may not live long enough", when it doesn't need to
如果其他人同意,可以删除此答案。
Gloop
或Mimsy
(或任何Wumpus<T>
)中的任何地方都存储了T
。
Rust并不关心你做什么,而是可以做什么。这两个结构之间没有签名差异:
struct Alpha<T> {
a: T,
}
struct Beta<T> {
b: fn(&T),
}
即,您无法区分这两者之间的区别,而Beta
可能会成为Alpha
而消费者没有明显的外部变化。一旦你有一个通用类型,你需要处理任何可能性。
您可以添加T: 'static
或添加生命周期并添加T: 'a
。
另见: