爲什麼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