fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x }
与使用两个生命周期相比,上述代码的优势是什么?是否存在以上代码可以工作但 2 个生命周期不工作的情况?
最佳答案
这实际上取决于您的用例。鉴于您编写的确切代码:
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str {
x
}
这里只使用一个生命周期是一个缺点,因为返回值只依赖于 x
参数,而不依赖于 y
参数。让我们想象一下这个用户代码:
let x_in = "paul".to_owned();
let out = {
let y_in = "peter".to_owned();
xory(&x_in, &y_in)
};
我们希望这能正常工作,因为 out
基本上是 x_in
。但是编译器提示:
<anon>:12:22: 12:26 error: `y_in` does not live long enough
<anon>:12 xory(&x_in, &y_in)
^~~~
<anon>:13:7: 14:2 note: reference must be valid for the block suffix following statement 1 at 13:6...
<anon>:13 };
<anon>:14 }
<anon>:11:39: 13:6 note: ...but borrowed value is only valid for the block suffix following statement 0 at 11:38
<anon>:11 let y_in = "peter".to_owned();
<anon>:12 xory(&x_in, &y_in)
<anon>:13 };
这是因为编译器假定(根据 xory
签名)xory
的输出引用了两个参数。因此,通常最好尽可能详细地指定生命周期,以避免不必要的条件/假设/参数之间的关系。
在某些情况下,您只需要使用一个生命周期(或稍微不同的解决方案):假设您希望根据某些条件返回 x
或 y
:
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() == 42 {
x
} else {
y
}
}
此处输出的生命周期可能取决于两个参数的生命周期,而我们在编译时不知道是哪一个。因此,我们必须做好最坏的打算,并这样做。
关于rust - 对多个参数使用相同的生命周期有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429233/