struct Point {
x: u32,
y: u32,
}
struct Line<'a> {
start: &'a Point,
end: &'a Point,
}
Run Code Online (Sandbox Code Playgroud)
Here, the only possible option for the start and end fields is to have a lifetime the same or longer than the Line variable that contains them. I can't even imagine how one will go about using a lifetime specifier to say that the fields have a shorter lifespan.
Why do I have to explicitly specify a lifetime here? Is elision not possible in this situation and if so why not?
She*_*ter 12
定义结构时,不会在结构的生命周期和字段的生命周期之间建立关系.正如您所指出的,字段中的引用必须比结构更长寿.
相反,你正在做的是提供一个"通用生命周期",它将在你创建结构时专门化.这与具有类型参数的结构类似:
struct Foo<T>
foo: T,
}
Run Code Online (Sandbox Code Playgroud)
构造结构时,编译器将插入适当的生命周期(或类型),然后检查所有内容是否仍然有效.
另一件事是,你可以针对指定寿命彼此:
struct Line<'a, 'b: 'a> {
start: &'a Point,
end: &'b Point,
}
Run Code Online (Sandbox Code Playgroud)
这说明start并且end可以有不同的寿命,只要寿命end 超过寿命start.
为什么编译器不对结构进行终身省略?似乎在Rust的精神下这样做
(强调我的)
我实际上相信Rust倾向于显性,特别是在定义顶级项目(如函数,结构)时.
功能的终身省略规则范围非常小,并且在RFc 141中凭经验可以获得高成功率(87%).这是一个非常好的人体工程学投资回报.
也许,在某些时候,将发生结构相似的省音,但一直没有一个足够大的问题还没有.如果你对此有强烈的兴趣,那么我强烈建议在用户论坛上寻求共识,进入开发者论坛,然后最终制作RFC.
RFC 2093添加了少量推理.在实现之前,您必须表示作为引用的泛型类型需要比引用更长:
struct Foo<'a, T: 'a> {
start: &'a T,
}
Run Code Online (Sandbox Code Playgroud)
在任何情况下你都不会想要这个绑定,所以在实现RFC之后,你可以说:
struct Foo<'a, T> {
start: &'a T,
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1600 次 |
| 最近记录: |