[英]What algorithms does the Rust compiler use to infer lifetime variables?
fn foo<'a>(x: &'a i32, y: &'a i32) {}
fn main() {
let a = 123;
{
let b = 234;
foo(&a, &b);
}
}
In the code above &a
and &b
should hopefully be references with different lifetimes. 在上面的代码中,
&a
和&b
应该是不同生命周期的引用。
How does the compiler infer the lifetime var 'a
for foo
? 编译器如何推断
foo
的生命周期变量'a
? As far as I can tell, it's not using a standard Hindley-Milner unification algorithm. 据我所知,它没有使用标准的Hindley-Milner统一算法。 The lifetime must be the inner scope or some intersection of the two lifetimes.
寿命必须是内部范围或两个生命周期的某个交集。
Is lifetime inference a completely separate process to the standard type inference? 终身推理是否与标准类型推断完全分开?
Does the compiler use intersection types or use some sub-type relationship between lifetimes to choose the most restricted lifetime? 编译器是否使用交集类型或使用生命周期之间的某些子类型关系来选择最受限制的生命周期?
Rust uses a modified Hindley-Milner unification algorithm because it has sub-typing relationships. Rust使用修改后的Hindley-Milner统一算法,因为它具有子类型关系。
For example, &'static T
is a sub-type of &'a T
for any 'a
. 例如,
&'static T
是&'a T
对任何'a
&'a T
子类型。
Your case is relatively easy, when the compiler sees the call foo(&a, &b)
it just unifies 'a
as the most restrictive of both lifetimes (which is the intersection, since lifetimes are lexical for now). 你的情况相对容易,当编译器看到调用
foo(&a, &b)
它只是将'a
统一为两个生命周期中最具限制性的(这是交集,因为生命周期现在是词法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.