gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:23:35 27 4
gpt4 key购买 nike

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

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
我知道为什么没有 contents参数和返回值的显式生命周期注释就不能编译代码- lifetime elision rules不适用于带有至少两个借入参数的函数。
但是我很好奇 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。哪一个是正确的?

最佳答案

lifetime elision下的rustonomicon中:

Each elided lifetime in input position becomes a distinct lifetime parameter.



您可以尝试将函数分配给错误的类型。编译器会告诉您函数的正确类型:
let x: () = search;
Playground
结果:
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也具有生命周期 'a,那么您应该能够做到这一点:
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
vec![query]
}
但这无法编译,因为 query的生存期不是 'a
Playground

关于rust - 当第二个参数用'a注释时,第一个参数的隐式生存期是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65127499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com