从我自己的理解和实验来看,这似乎是正确的,但我还没有找到记录它的权威来源。 Rust by Example 有一个bounds https://doc.rust-lang.org/rust-by-example/scope/lifetime/lifetime_bounds.html部分说:
T: 'a
:所有参考文献T
必须比生命更长久'a
.
#[derive(Debug)]
struct Ref<'a, T: 'a>(&'a T);
// `Ref` contains a reference to a generic type `T` that has
// an unknown lifetime `'a`. `T` is bounded such that any
// *references* in `T` must outlive `'a`. Additionally, the lifetime
// of `Ref` may not exceed `'a`.
然而,这看起来像是一个糟糕的演示,因为T: 'a
绑定似乎不影响的行为Ref
。我所做的任何尝试都是为了构建一个T
比'a
有或没有受到阻碍T: 'a
。更重要的是,定义了通用参考without生命周期界限可以作为一个传递with it:
fn f<'a, T>(r: &'a T) {
g(r) // this compiles
}
fn g<'a, T: 'a>(r: &'a T) {
// ...
}
Rust 参考文献中的一些示例具有类似的结构通用参数 https://doc.rust-lang.org/reference/items/generics.html部分 (struct Ref<'a, T> where T: 'a { r: &'a T }
),但没有详细说明。我浏览了那里的文档,那些关于参考文献和关于生命周期的文档,但找不到链接。
So does &'a T
imply T: 'a
?如果是这样,这在哪里记录?为什么这些资源有这种不必要的限制?如果没有,规则是什么?
Yes, &'a T
确实意味着T: 'a
.
总是要求引用对象的寿命必须超过引用的寿命,因为它对于安全构建是必要的。但是,在 Rust 1.31 之前,不会推断界限,必须显式提供,如下所示these https://stackoverflow.com/questions/38626644/why-does-the-rust-compiler-request-i-constrain-a-generic-type-parameters-lifeti 问题 https://stackoverflow.com/questions/41794800/why-is-the-bound-t-a-required-in-order-to-store-a-reference-a-t.
It was RFC #2093:推断寿命 https://github.com/rust-lang/rfcs/blob/master/text/2093-infer-outlives.md让编译器推断这些边界,从而允许用户忽略它们。从那时起,Rust by Examples 和 Rust Reference 片段就被过度指定,并且T: 'a
不再需要。
请参阅参考资料中的其他地方特质和寿命界限 https://doc.rust-lang.org/beta/reference/trait-bounds.html#implied-bounds:
有时会推断出类型良好形成所需的生命周期界限。
fn requires_t_outlives_a<'a, T>(x: &'a T) {}
类型参数T
需要比'a
对于类型&'a T
格式良好。这是推断出来的,因为函数签名包含类型&'a T
仅当以下情况下才有效T: 'a
holds.
至少有一个地方&'a T
不会自动推断T: 'a
那就是在为特征定义关联类型时()但编译器会引导您显式添加它:
trait MakeRef<'a> {
type Type;
}
impl<'a, T> MakeRef<'a> for Vec<T> {
type Type = &'a T;
}
error[E0309]: the parameter type `T` may not live long enough
--> src/lib.rs:6:17
|
6 | type Type = &'a T;
| ^^^^^ ...so that the reference type `&'a T` does not outlive the data it points at
|
help: consider adding an explicit lifetime bound...
|
5 | impl<'a, T: 'a> MakeRef<'a> for Vec<T> {
| ++++
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)