Why can the lifetimes not be elided in a struct definition?

Raj*_*ajV 11 lifetime rust

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)

  • 从这个答案中不清楚为什么在声明结构时生命周期是必要的*. (2认同)
  • @Shepmaster,“结构声明没有生命周期省略,尽管我认为编译器可以自动为每个生命周期添加‘a’”。问题恰恰在于:**为什么**编译器不对结构进行生命周期省略?这样做似乎符合 Rust 的精神,而且在我看来,这样做是有充分理由的。我认为您的答案根本没有解决这个问题,它只提供了显式生命周期声明的示例,所以我很惊讶它被接受了。 (2认同)
  • @AxiomaticNexus 我个人会坚持一生,直到某些事情迫使我使用多次。如果我正在编写一个公共 API,并且在发布后我会犹豫是否要更改,那么情况可能会改变。 (2认同)