为什么可以在函数上指定多个泛型生命周期?
当您创建一个以多个引用作为输入的函数,并返回一个引用作为输出时,您需要指定输出引用的生命周期与哪个或多个输入引用相关联。这是有道理的。
没有意义的事情是为什么您需要定义多个通用生命周期。你只能有一个返回值。
在这里,我们定义了'a和'b- 两个通用生命周期。在返回值上,我们可以指定'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 {}
这涵盖了所有场景(至少在这个简单示例中),并且这些场景都不需要定义一个以上的通用生命周期(定义'b)。
是否有过需要定义多个通用生命周期的情况?
回答
如果您在返回值只有一个一辈子,你不必须在功能上超过一个人一生中的参数。您询问的所有这些示例都是有效的 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
允许不必要的生命周期参数有名称,但因为它们只使用一次,所以它们不会对函数强加任何生命周期关系,并且可能会被省略(省略)。
是否有过需要定义多个通用生命周期的情况?
当然,例如,当您的函数具有多个输出生命周期时:
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)
}
这个相当愚蠢的函数返回一个包含两个引用的元组:一个指向 3 个字符串中最长的一个,另一个总是引用arg3. 第一个引用的生命周期必须超过所有三个参数;第二个引用只需要比arg3.
相关问题
- 什么时候在结构中定义多个生命周期有用?
- 用非常简单的术语来说,什么是终身省略?(以及其他链接在那里的问题)
- 为什么在 Rust 中需要明确的生命周期?
- Since you've linked to [When is it useful to define multiple lifetimes in a struct?](https://stackoverflow.com/q/29861388/155423), I'll point out that if you accept those answers, then you almost need to have a function to _construct_ those types in the first place.