为什么可以在函数上指定多个泛型生命周期?

Why can you specify multiple generic lifetimes on functions?

当您创建一个将多个引用作为输入并return一个引用作为输出的函数时,您需要指定输出引用的生命周期与哪个或多个输入引用相关联。这是有道理的。

没有意义的是为什么您需要定义多个通用生命周期。您只能有一个 return 值。

在这里,我们定义了 'a'b - 两个通用生命周期。在 return 值上,我们可以指定 'a'b - 不能同时指定:

fn foo<'a, 'b>(ref1: &'a str, ref2: &'b str) -> &'a str {}

这似乎可以缩短为:

fn foo<'a>(ref1: &'a str, ref2: &str) -> &'a str {}

如果我们想将输出的生命周期与第二个输入参数联系起来,我们可以这样做:

fn foo<'a>(ref1: &str, ref2: &'a str) -> &'a str {}

如果我们想将它与两者联系起来,我们可以这样做:

fn foo<'a>(ref1: &'a str, ref2: &'a str) -> &'a str {}

这涵盖了所有场景(至少在这个简单示例中),其中 none 需要定义多个通用生命周期(定义 'b)。

是否存在需要定义多个通用生命周期的情况?

如果您的 return 值中只有一个生命周期,则您 不需要函数的多个生命周期参数。您询问的所有这些示例都是有效的 Rust 代码:

fn foo<'a, 'b>(ref1: &'a str, ref2: &'b str) -> &'a str {} // borrows ref1 ('b is unnecessary)
fn foo<'a>(ref1: &'a str, ref2: &str) -> &'a str {}        // borrows ref1 (same as above)
fn foo<'a>(ref1: &str, ref2: &'a str) -> &'a str {}        // borrows ref2
fn foo<'a>(ref1: &'a str, ref2: &'a str) -> &'a str {}     // borrows both ref1 and ref2

不必要的生命周期参数允许有名字,但因为它们只被使用一次,所以它们不会对函数施加任何生命周期关系,并且可以被省略(省略) ).

Is there ever a case where you do need to define more than one generic lifetime?

当然可以,例如,当您的函数具有多个输出生命周期时:

fn longest_last<'a, 'b: 'a>(arg1: &'a str, arg2: &'a str, arg3: &'b str) -> (&'a str, &'b str) {
    (longest(arg1, longest(arg2, arg3)), arg3)
}

这个相当愚蠢的函数 return 是一个包含两个引用的元组:一个指向 3 个字符串中最长的一个,另一个始终指向 arg3。第一个引用的生命周期必须超过所有三个参数;第二个引用只需要比 arg3.

相关问题

  • (以及那里链接的其他问题)