考虑以下 Rust 程序:
fn f<'a>(x: &'a i32) {
unimplemented!();
}
fn main() {
f::<'static>;
}
编译时,输出如下编译错误:
error: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present
--> src/main.rs:6:9
|
6 | f::<'static>;
| ^^^^^^^
|
note: the late bound lifetime parameter is introduced here
--> src/main.rs:1:6
|
1 | fn f<'a>(x: &'a i32) {
| ^^
让我们这样修改程序:
fn f<'a, 'b>(x: &'a i32) -> &'b i32 {
unimplemented!();
}
fn main() {
f::<'static>;
}
出于某种奇怪的原因,现在可以编译,没有任何编译错误。这是为什么呢?如果第一个程序中的生命周期参数 'a 是后期绑定的,为什么它不应该在第二个程序中后期绑定呢?请注意,我在第一个程序和第二个程序之间所做的唯一更改是添加另一个生命周期参数和依赖于这个新生命周期参数的返回类型。
正如评论之一所写,带有
f<'a, 'b>
和 f::<'static>
的第二个程序当前会产生警告(Rust 1.80):
warning: cannot specify lifetime arguments explicitly if late bound lifetime parameters are present
--> src/main.rs:6:9
|
1 | fn f<'a, 'b>(x: &'a i32) -> &'b i32 {
| -- the late bound lifetime parameter is introduced here
...
6 | f::<'static>;
| ^^^^^^^
|
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #42868 <https://github.com/rust-lang/rust/issues/42868>
= note: `#[warn(late_bound_lifetime_arguments)]` on by default
至于发生这种情况的原因,警告中链接的 GitHub 问题对此进行了解释:
仅在 2017 年将其设置为硬错误会导致损坏的情况下,才会将其报告为 lint。 目的是产生错误,一般来说,lint 只是给人们一些时间来修复代码的一种方法。
所以,简而言之,这有时是一个警告,以防出现错误会破坏现有的 Rust 代码。