Given a Rust program, which compiles correctly, can I get the compiler to tell me what the elided lifetimes were inferred to be?
Lifetimes are what the Rust compiler uses to keep track of how long references are valid for. Checking references is one of the borrow checker's main responsibilities. Lifetimes help the borrow checker ensure that you never have invalid references.
You can't. A lifetime parameter does not allow you to choose how long a value lives, it only allows you to communicate to the compiler that two or more references are "related" to the same memory and are expected to share the same lifetime.
'_ , the anonymous lifetime Rust 2018 allows you to explicitly mark where a lifetime is elided, for types where this elision might otherwise be unclear. To do this, you can use the special lifetime '_ much like you can explicitly mark that a type is inferred with the syntax let x: _ = ..; .
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 impl
s or struct
s if elision was permitted there too).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With