Skip to content

Ch 10.3: explain why lifetimes are necessary and rust design choices #2296

@akiross

Description

@akiross

This is a proposal to introduce, in the lifetime chapter 10.3, an explanation of why lifetime annotations are necessary at all. I think the concept of lifetime annotations can be understood easily, but I think that - being so peculiar to rust - it needs more grounded explanations to be fully assimilated in the reader.

The Book explains that, when multiple annotations are possible, then we have to annotate the lifetimes, and it is also explained that the lifetimes are tied to the signature of the function and not its body. In my case, this last part did not click until I understood why the lifetimes are necessary at all and, for example, cannot be inferred by the compiler.

An explanation exists and it is discussed and explained elsewhere, by yourself (book authors):

Yes, Rust could look at function bodies and infer lifetimes. Not doing so is a choice. The reason is the same reason we don’t infer the types of functions (lifetimes are types!). Rust views the function signature as the holy contract, and the body is expected to follow it. If we inferred the signature, changing the body could change the type. And if that happened, you could create breaking changes without realizing it.

I think this snippet is very helpful and it would be great to have it in the documentation. My proposal is to add it as a short paragraph just after the lifetime elision one or before the summary.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions