如何将一个字段的生存期指定为其他字段的组合?

时间:2019-07-08 16:53:04

标签: rust lifetime

我有一个函数,可以在三个引用字段的结构中存储两个参数。我不知道如何指定此第三个结果字段的生存期,这是该函数的前两个参数的生存期的组合。

我尝试将前两个参考参数存储在结构中。这工作得很好,没有意义。更有趣的是,我在下面显示的情况下没有解决方案。

我知道这段代码没有任何意义;它只是显示了问题。

// This function can be found in "Lifetime Annotations in Function Signatures" of the Rust manual
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

// Here comes the interesting part; 1st the result type of my function
struct SillyResult<'a, 'b, 'c> {
    arg1: &'a str,
    arg2: &'b str,
    result: &'c str,
}

// ... and now the function, that does not compile and shall be corrected
fn silly_fkt<'a, 'b, 'c: 'a + 'b>(arg1: &'a str, arg2: &'b str) -> SillyResult<'a, 'b, 'c> {
    // Neither the following line ...
    // SillyResult<'a, 'b, 'c>{arg1: arg1, arg2: arg2, result: longest(arg1, arg2)}
    // ... nor the following line work
    SillyResult {
        arg1,
        arg2,
        result: longest(arg1, arg2),
    }
}

这个想法是将生存期'a'b组合为生存期'c。 但是,它会为抱怨生命周期带来很多错误:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
  --> src/lib.rs:25:17
   |
25 |         result: longest(arg1, arg2),
   |                 ^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'b as defined on the function body at 18:18...
  --> src/lib.rs:18:18
   |
18 | fn silly_fkt<'a, 'b, 'c: 'a + 'b>(arg1: &'a str, arg2: &'b str) -> SillyResult<'a, 'b, 'c> {
   |                  ^^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:25:31
   |
25 |         result: longest(arg1, arg2),
   |                               ^^^^
note: but, the lifetime must be valid for the lifetime 'c as defined on the function body at 18:22...
  --> src/lib.rs:18:22
   |
18 | fn silly_fkt<'a, 'b, 'c: 'a + 'b>(arg1: &'a str, arg2: &'b str) -> SillyResult<'a, 'b, 'c> {
   |                      ^^
   = note: ...so that the expression is assignable:
           expected SillyResult<'a, 'b, 'c>
              found SillyResult<'_, '_, '_>

我尝试将silly_fkt的最后一行更改为

SillyResult<'a, 'b, 'c>{ arg1, arg2, result: longest(arg1, arg2) }

但这不起作用。

silly_fkt的正确代码是什么?

1 个答案:

答案 0 :(得分:5)

您的语义向后year = rep(rep(`insert year start`:`insert year end`), times = dt$Name %>% unique %>% length)) :表示'c: 'a 生存期 'c,在这里您想说{{1 }} 的寿命超过了 'a(因此,您可以提供寿命为'c的引用,其中预期寿命为'a的引用)。因此,您需要以另一种方式编写寿命约束。

您可以编写'a,但我发现使用'c子句更容易阅读:

<'a: 'c, 'b: 'c, 'c>
相关问题