What algorithms does the Rust compiler use to define lifetime variables?
fn foo<'a>(x: &'a i32, y: &'a i32) {}
fn main() {
let a = 123;
{
let b = 234;
foo(&a, &b);
}
}
The above code &a
and &b
hopefully will have links with different lifetimes.
How does the compiler infer the var resource 'a
for foo
? As far as I can tell, it doesn't use the standard Hindley-Milner unification algorithm. The lifespan must be an inner region or some intersection of two lifespan.
Is inference for life a completely separate process for standard type inference?
Does the compiler use intersection types or does it use some kind of time-type relationship between lifetimes to choose the most limited lifetime?
Rust uses a modified Hindley-Milner unification algorithm because it has sub-printing relationships.
For example, &'static T
is a subtype &'a T
for anyone 'a
.
Your case is relatively simple, where the compiler sees the call foo(&a, &b)
, it just concatenates 'a
as the most restrictive of the two lifetimes (which is an intersection, since the lifetimes are lexical at the moment).
source to share