为什么Rust编译器发出一个错误,要求我限制下列结构中泛型参数的生存期?Rust编译器为什么要求我限制泛型类型参数的生存期(错误E0309)?
pub struct NewType<'a, T> {
x: &'a T,
}
error[E0309]: the parameter type `T` may not live long enough
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
我可以通过改变
pub struct NewType<'a, T>
where
T: 'a,
{
x: &'a T,
}
我不明白为什么它是必要的T: 'a
部件添加到结构定义修复它。我想不到T
中包含的数据可能会超过对T
的引用。 x
的引用需要超过NewType
结构,如果T
是另一个结构,那么它需要符合它包含的任何引用的相同条件。
是否有一个具体的例子,这种类型的注释是必要的,或者是锈编译器只是迂腐?
这会让你更加困惑于相关的类型。你必须绑定 :: Associated:'a *即使你已经绑定了T的一生,这对我来说并没有什么意义。 –
LinearZoetrope