gpt4 book ai didi

rust - 当输入非常清楚时,为什么借用检查器需要输出生命周期标签?

转载 作者:行者123 更新时间:2023-11-29 08:10:27 26 4
gpt4 key购买 nike

为什么借用检查器会对下面代码中的生命周期感到困惑

fn main() {
let ss = "abc"; // lets say 'a scope
let tt = "def"; // lets say 'b scope
let result = func(ss, tt);
}

fn func(s: &str, t: &str) -> &str {
t
}
| fn func(s: &str, t: &str) -> &str {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `s` or `t`

为什么这段代码中的内容如此重要?我是否遗漏了一些非常重要的边缘案例?

但是当我用生命周期标签对它们进行注释时,它就起作用了。

fn func<'a>(s: &'a str, t: &'a str) -> &'a str {
t
}

我读到每个变量绑定(bind) (let) 创建一个隐式作用域,那么为什么 2 个输入变量具有相同的作用域。纠正我,如果我 worng。在函数调用'func'栈中,"s"会先被压入,然后是"t",所以"s"和"t"有不同的生命周期。首先删除“t”,然后删除“s”。

最佳答案

你还没有告诉编译器返回值是否可以从st、两者借用,或者两者都不借用:

fn from_s<'a, 'b>(s: &'a str, t: &'b str) -> &'a str {
// can be abbreviated: fn from_s<'a>(s: &'a str, t: &str) -> &'a str
s
}

fn from_t<'a, 'b>(s: &'a str, t: &'b str) -> &'b str {
// can be abbreviated: fn from_t<'a>(s: &str, t: &'a str) -> &'a str
t
}

fn from_both<'a>(s: &'a str, t: &'a str) -> &'a str {
if s < t {
s
} else {
t
}
}

fn from_neither<'a, 'b>(s: &'a str, t: &'b str) -> &'static str {
// can be abbreviated: fn func(s: &str, t: &str) -> &'static str
"foo"
}

如果你没有写'static,编译器会假设最后一个不是你想要的。但是您仍然需要在前三个之间消除歧义。

要了解差异为何重要,请考虑这样的调用者

fn main() {
let s = String::from("s");
let r;
{
let t = String::from("t");
r = from_s(&s, &t);
// t goes out of scope
}
println!("{}", r);
}

如果编译器允许您调用 from_t 而不是 from_s,您将打印一个已经被释放的字符串。

关于rust - 当输入非常清楚时,为什么借用检查器需要输出生命周期标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103238/

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