为什么不能将引用的生命周期推断为所有上下文可能性中最短的?
Why can't the lifetime of a reference be deduced as the shortest of all the contextual possibilities?
这是一个代码示例,我在其中测试了两个 &str
和 return 其中之一:
fn bad_longest(s1: &str, s2: &str) -> &str {
if s1.len() >= s2.len() { s1 } else { s2 }
}
它没有编译请求显式生命周期,所以我提供了它们:
fn longest<'r, 'a, 'b>(s1: &'a str, s2: &'b str) -> &'r str
where
'a: 'r,
'b: 'r
{
if s1.len() >= s2.len() { s1 } else { s2 }
}
现在,以下测试顺利通过:
static STATIC: &str = "123";
fn main() {
let auto = "123456";
let dyn_ = String::from("123456789");
println!(
"{}",
longest(
longest(STATIC, auto),
dyn_.as_str()
)
);
}
我的问题是:我手动提供的生命周期不是可以从上下文中明显推导出来的吗?我是否遗漏了任何用例?
函数签名中省略的生命周期永远不会从它们的使用方式中推断出来。还有一些simple rules for inferring elided lifetimes,完全基于签名本身:
- Each elided lifetime in the parameters becomes a distinct lifetime parameter.
- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.
In method signatures there is another rule
- If the receiver has type &Self or &mut Self, then the lifetime of that reference to Self is assigned to all elided output lifetime parameters.
您的函数有两个非 self
参数,因此 none 这些规则可以为 return 值提供生命周期,因此需要明确的生命周期。
这是一个代码示例,我在其中测试了两个 &str
和 return 其中之一:
fn bad_longest(s1: &str, s2: &str) -> &str {
if s1.len() >= s2.len() { s1 } else { s2 }
}
它没有编译请求显式生命周期,所以我提供了它们:
fn longest<'r, 'a, 'b>(s1: &'a str, s2: &'b str) -> &'r str
where
'a: 'r,
'b: 'r
{
if s1.len() >= s2.len() { s1 } else { s2 }
}
现在,以下测试顺利通过:
static STATIC: &str = "123";
fn main() {
let auto = "123456";
let dyn_ = String::from("123456789");
println!(
"{}",
longest(
longest(STATIC, auto),
dyn_.as_str()
)
);
}
我的问题是:我手动提供的生命周期不是可以从上下文中明显推导出来的吗?我是否遗漏了任何用例?
函数签名中省略的生命周期永远不会从它们的使用方式中推断出来。还有一些simple rules for inferring elided lifetimes,完全基于签名本身:
- Each elided lifetime in the parameters becomes a distinct lifetime parameter.
- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.
In method signatures there is another rule
- If the receiver has type &Self or &mut Self, then the lifetime of that reference to Self is assigned to all elided output lifetime parameters.
您的函数有两个非 self
参数,因此 none 这些规则可以为 return 值提供生命周期,因此需要明确的生命周期。