It appears to me that the purpose of the RFC on lifetime elision is to use heuristics to decide on lifetime specifications. But can’t we do better than that? Can’t we do proper lifetime inference?
For example:
fn foo(x: &int, y: &int) -> &int {
if *x > 50 {
x
}
else {
y
}
}
Unless I’m misunderstanding something, according to the RFC (as well as in current Rust builds) the above code requires explicit lifetime annotations to compile, like so:
fn foo<'a>(x: &'a int, y: &'a int) -> &'a int {
...
}
But it seems like the compiler ought to be able to infer this. In fact, in a sense it seems like it already does. If I try to compile this:
fn foo<'a, 'b>(x: &'a int, y: &'b int) -> &'a int {
...
}
It refuses to compile, giving an error about the lifetimes. So the compiler knows that this particular lifetime specification makes no sense with respect to the code inside the function. So why not take its analysis a step further and have it work backwards from the return value to figure out which inputs it could possibly come from, and infer a minimal correct lifetime specification from that?
Of course, this is a trivial example. But aside from code that uses unsafe blocks to do weird things, it appears to me that lifetime specifications (at least for functions) are pretty mechanical and deterministic. It feels like busy work with only one correct answer that the compiler ought to be able to infer.
I could absolutely be missing something here–I’m relatively new to Rust. So my apologies if I’m just being ignorant. But I’m concerned about locking Rust into heuristics as outlined in the RFC if more robust lifetime inference is a feasible alternative.