对多个参数使用相同的生命周期有什么好处?

What is the advantage of using the same lifetime for multiple arguments?

fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x }

与使用两个生命周期相比,上述代码有什么优势?是否存在以上代码可以工作但 2 个生命周期不工作的情况?

在相同的生命周期内,你说 return 值可以从 xy 借用,所以从函数体的角度来看,它是更灵活。 从调用者来看,它更具限制性,因为只要结果被保留,xy 都需要有效,而不仅仅是 x(比如)。

这真的取决于您的用例。鉴于您编写的确切代码:

fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { 
    x 
}

这里只使用一个生命周期是一个缺点,因为return值只依赖于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 的输出引用了两个参数。因此,通常最好尽可能详细地指定生命周期,以避免参数之间不必要的 conditions/assumptions/relationships。


在某些情况下,您只需要使用一个生命周期(或稍微不同的解决方案):假设您希望根据某些条件 return xy

fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { 
    if x.len() == 42 { 
        x
    } else {
        y
    }
}

此处输出的生命周期可能取决于两个参数的生命周期,而我们在编译时不知道是哪一个。所以我们要做好最坏的打算,就这样去做。