当第二个参数用'a注释时,第一个参数的隐式生命周期是多少?

在阅读Rust Book 的第 12.4 章时,我偶然发现了这个函数:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    vec![]
}

我理解为什么在没有contents参数和返回值的显式生命周期注释的情况下代码不能编译-生命周期省略规则不适用于具有至少两个借用参数的函数。

但我很好奇这个query论点的隐含生命周期注释是什么。我可以想到两种情况:

// Scenario 1
pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
    vec![]
}
// Scenario 2
pub fn search<'a, 'b>(query: &'b str, contents: &'a str) -> Vec<&'a str> {
    vec![]
}

两种情况query都可以编译,因此获得生命周期'a'b. 哪一个是正确的?

回答

rustonomicon, 在终身省略下:

输入位置中的每个省略的生命周期都成为一个不同的生命周期参数。


您可以尝试将该函数分配给错误的类型。编译器会告诉你函数的正确类型:

let x: () = search;

操场

结果:

error[E0308]: mismatched types
 --> src/main.rs:6:17
  |
6 |     let x: () = search;
  |            --   ^^^^^^ expected `()`, found fn item
  |            |
  |            expected due to this
  |
  = note: expected unit type `()`
               found fn item `for<'r, 'a> fn(&'r str, &'a str) -> Vec<&'a str> {search}`

所以,你的函数类型是:

for<'r, 'a> fn(&'r str, &'a str) -> Vec<&'a str> {search}

此外,如果query也有 life 'a,你应该能够做到这一点:

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    vec![query]
}

但这无法编译,因为它query的生命周期不是'a

操场


以上是当第二个参数用'a注释时,第一个参数的隐式生命周期是多少?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>