Consider the following two definitions for the struct A
:
// Option 1
struct A<'a>(&'a str, &'a str);
// Option 2
struct A<'a, 'b>(&'a str, &'b str);
If I understand correctly, any valid program that uses option 1 would also be valid with option 2, as long as A<'a>
is replaced with A<'a, 'a>
(though the reverse might not be true).
- Is that correct?
AFAIK yes.
- If it is correct, what are the advantages to using option 1 over option 2? Specifically, is there any impact on performance?
Performance (at runtime, not compile time) will be unaffected, as lifetimes cannot affect runtime performance. The advantage is less lifetimes on the struct and therefore less headache for its user. As most of the times option 1 is enough, this gives better readability.
- Has it ever been considered to automatically assign each reference field in a struct a different lifetime parameter by default if no explicit lifetime parameters are provided? (Similar to lifetime elision but for structs.)
Not any program that uses one lifetime can be replaced by two lifetimes (without any relationship between them), and moreover most of the times two lifetimes will not be more flexible than one lifetime. Therefore, such automatic elision may end up being a pessimization most of the times. Maybe a more sophisticated analysis (for example considering variance) can be better, but that also has drawbacks and I'm not aware of any such proposal.
However, it was proposed (and eventually declined) to allow omitting the lifetimes declaration on the struct, and infer lifetimes based on their names that appear in the struct definition (and not only for structs): https://rust-lang.github.io/rfcs/2115-argument-lifetimes.html.