Is there a way to obtain elided lifetime parameters from the Rust compiler?
Asked Answered
W

1

10

Given a Rust program, which compiles correctly, can I get the compiler to tell me what the elided lifetimes were inferred to be?

Waldheim answered 10/1, 2016 at 10:59 Comment(4)
Actually, it is called lifetime elision and you can find the rules here: doc.rust-lang.org/stable/nomicon/lifetime-elision.htmlSamurai
@TiborBenke Surely "elision" is what the code author does; the compiler can infer the elided values. In any case, I didn't mean "which lifetimes are elided" - that should be obvious by their absence, I meant what are the values of those lifetimes? Updated the question to reflect thatWaldheim
@TiborBenke I guess what you are really saying is that the elision rules are so simple that the lifetimes can be deduced trivially: there is only one lifetime to consider and it is used in all lifetime positions.Waldheim
Yes, the compiler follows these rules to infer/expand the concrete lifetimes.Samurai
W
5

The cases where the compiler (currently1) can allow elided lifetimes are actually so simple that there isn't much the compiler could tell you about what it inferred:

Given a function, all elided lifetimes have the same value.

The compiler doesn't accept elided lifetimes in cases where it would have a choice to make. The exception is in methods, but tying all lifetimes to self is nearly always what is intended, so it makes sense for it to make this assumption.

[1] If a future version of Rust performed more sophisticated inference on elided lifetimes, then this question might have a far less trivial answer. For example the compiler could analyse the entire codebase to deduce a coherent set of lifetimes for all functions (or impls or structs if elision was permitted there too).

Waldheim answered 10/1, 2016 at 13:3 Comment(1)
If a future version of Rust [...] — This is very unlikely, as Rust tends to favor explicit code. The reason that lifetime inference was added is because it had a small number of simple rules and those rules cleaned up something like 87% of cases that used lifetimes.Martita

© 2022 - 2024 — McMap. All rights reserved.