gpt4 book ai didi

rust - 为什么不能将引用的生存期推论为所有上下文可能性中最短的?

转载 作者:行者123 更新时间:2023-12-03 11:42:56 25 4
gpt4 key购买 nike

这是一个代码示例,我在其中测试两个&str并返回其中一个:

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参数,因此这些规则都不能为返回值指定有效期,因此需要显式的有效期。

关于rust - 为什么不能将引用的生存期推论为所有上下文可能性中最短的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63224750/

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