gpt4 book ai didi

rust - 如何将一个字段的生命周期指定为其他字段的组合?

转载 作者:行者123 更新时间:2023-11-29 07:57:57 25 4
gpt4 key购买 nike

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

我尝试将前两个引用参数存储在结构中。这工作得很好,没有兴趣。更有趣的是我在下面展示的案例,我没有解决方案。

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

// 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 的正确代码是什么?

最佳答案

你有 : 的语义向后:'c: 'a意味着 'c 长寿'a ,你想说的地方 'c 生命周期超过 'a (以便您可以提供生命周期 'a 的引用,其中生命周期为 'c 是预期的)。所以你需要反过来写生命周期约束。

你可以写<'a: 'c, 'b: 'c, 'c> , 但我发现使用 where 更容易阅读子句:

fn silly_fkt<'a, 'b, 'c>(arg1: &'a str, arg2: &'b str) -> SillyResult<'a, 'b, 'c>
where
'a: 'c,
'b: 'c,
{
SillyResult {
arg1,
arg2,
result: longest(arg1, arg2),
}
}

关于rust - 如何将一个字段的生命周期指定为其他字段的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com