Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 874
Peter Hall Avatar asked Jan 10 '16 10:01

Peter Hall


People also ask

What is a lifetime parameter rust?

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.

How do you specify lifetime in Rust?

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.

What is Anonymous lifetime rust?

'_ , 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: _ = ..; .


1 Answers

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).

like image 172
Peter Hall Avatar answered Sep 23 '22 02:09

Peter Hall