Rust 对多个参数使用相同的生存期有什么好处? fn xory

Rust 对多个参数使用相同的生存期有什么好处? fn xory,rust,lifetime,lifetime-scoping,Rust,Lifetime,Lifetime Scoping,在相同的生命周期内,您所说的返回值可以从x或y借用,因此从函数体的角度来看,它更灵活。 从调用者的角度来看,它更具限制性,因为只要结果保持不变,x和y都需要有效,而不仅仅是x(比如)。这实际上取决于您的用例。根据您编写的确切代码: fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x } 我们希望这可以正常工作,因为out基本上是xu-in。但编译器抱怨: let x_in = "paul".to_own

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

这实际上取决于您的用例。根据您编写的确切代码:

fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x }
我们希望这可以正常工作,因为
out
基本上是
xu-in
。但编译器抱怨:

let x_in = "paul".to_owned();
let out = {
    let y_in = "peter".to_owned();
    xory(&x_in, &y_in)
};

在这里,输出的生存期可以取决于两个参数的生存期,我们不知道编译时是哪一个。因此,我们必须做好最坏的准备,并这样做。

哦,如果输出取决于两个输入,那么输出必须统一。
let x_in = "paul".to_owned();
let out = {
    let y_in = "peter".to_owned();
    xory(&x_in, &y_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     };
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { 
    if x.len() == 42 { 
        x
    } else {
        y
    }
}