![](/img/trans.png)
[英]Tell the Rust compiler that the lifetime of a parameter is always identical to a struct's lifetime
[英]Why does the Rust compiler request I constrain a generic type parameter's lifetime (error E0309)?
为什么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: 'a
一部分。 我不能想办法是包含在数据T
能活得比引用T
。 x
的引用需要比NewType
结构更长,如果T
是另一个结构,那么它也需要满足它包含的任何引用的相同条件。
是否有一个特定的例子,这种类型的注释是必要的,还是Rust编译器只是迂腐?
什么T: 'a
是说T
中的任何引用必须比'a
更长。
这意味着你不能做以下事情:
let mut o: Option<&str> = Some("foo");
let mut nt = NewType { x: &o }; // o has a reference to &'static str, ok.
{
let s = "bar".to_string();
let o2: Option<&str> = Some(&s);
nt.x = &o2;
}
这将是危险的,因为nt
将有一个悬空参考s
块之后。 在这种情况下,它也会抱怨o2
寿命也不长。
我不能想办法,你可以有一个&'a
东西参考包含短寿命参考,并明确了编译器知道该以某种方式(因为它告诉你添加的约束)。 但是我认为在某些方面有助于说明限制,因为它使借用检查器不那么神奇:你可以仅仅通过类型声明和函数签名来推理它,而不必看看如何定义字段(通常是实现不在文档中的细节)或如何执行函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.