【发布时间】:2016-12-02 06:31:32
【问题描述】:
为什么 Rust 编译器会发出一个错误,要求我在以下结构中限制泛型参数的生命周期?
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 是另一个结构,那么它包含的任何引用也需要满足相同的标准。
是否存在需要这种类型的注释的具体示例,或者 Rust 编译器只是迂腐?
【问题讨论】:
-
这会与关联类型混淆。你必须绑定
::Associated: 'a 即使你已经绑定了 T 的生命周期,这不会对我来说真的很有意义。