-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Description
I have decided, as my time permits, to resume trying to help improve the Rust documentation.
In the past, I told you that I felt that the first version of the Rust Book's explanation of lifetimes was inadequate because while it explained the syntax, it was woefully short on semantics. The description simply didn't clearly convey what lifetime annotations meant.
In the second version, the discussion of lifetime annotations in function headers is much improved in this regard.
But in Section 10.3, there is a subsection, "Lifetime Annotations in Struct Definitions", that in my opinion reverts back to the tendency to explain the syntax and forget the semantics. This section simply doesn't explain what it means to declare a lifetime in a struct header and then the lifetime of a reference in a field.
You are very careful in the discussion of lifetimes in fn declarations to explain that
fn foo<'a>(.....)
means that "there exists a lifetime named a". In effect, the lifetime 'a is declared here, no more, no less. You then show how that declared lifetime can be used to make assertions about the relationship among the lifetimes of references. Fine.
But in the case of structs, i believe it is true that
struct foo<'a>
means that instances of this struct have lifetimes of 'a or less. Declaring that the lifetime of a reference in a field in foo has a lifetime of 'a means that that reference must live at least as long as struct foo.
The little section about lifetimes in structs doesn't say this. Having read the discussion of lifetimes in fn headers, and how they are used to relate the lifetimes of multiple references, it was a complete mystery to this reader why a struct with a single field that is reference would still require lifetime annotations, since the syntax is similar to functions, but the meaning is completely different. The answer is, of course, that those annotations make an assertion about the lifetime of the struct itself to that of the reference it contains. To find this out, I had to do some web searching and found an explanation of Rust lifetimes written by someone not charged with writing documentation for the project.