英文:
Rust lifetime limitation
问题
fn f<'a: 'b, 'b>(x: &'a i32, mut y: &'b i32) -> &'b i32 {
y = x;
y
}
let long_var = 1;
let long_lifetime = &long_var;
{
let short_var = 2;
let short_lifetime = &short_var;
// it works, why?
let x = f(short_lifetime, long_lifetime);
};
在函数`f`中有限制`'a: 'b`,所以为什么`let x = f(short_lifetime, long_lifetime);`会起作用?
翻译结果:
在函数`f`中有限制`'a: 'b`,所以为什么`let x = f(short_lifetime, long_lifetime);`会起作用?
<details>
<summary>英文:</summary>
fn f<'a: 'b, 'b>(x: &'a i32, mut y: &'b i32) -> &'b i32 {
y = x;
y
}
let long_var = 1;
let long_lifetime = &long_var;
{
let short_var = 2;
let short_lifetime = &short_var;
// it works, why?
let x = f(short_lifetime, long_lifetime);
};
There is limitation `'a: 'b` in the function `f`, so why `let x = f(short_lifetime, long_lifetime); ` works?
</details>
# 答案1
**得分**: 4
因为函数参数中的生命周期是_边界_而不是严格的生命周期。所以当你调用 `f(short_lifetime, long_lifetime)` 时,编译器会尝试找到生命周期 `'a` 和 `'b`,使得:
- `short_lifetime` 至少与 `'a` 一样长(_但它可能存在更长_),
- `long_lifetime` 至少与 `'b` 一样长(_但它可能存在更长_),
- `'a` 至少与 `'b` 一样长(但它们可以相等),
- 返回的值的生命周期至多与 `'b` 一样长(但它可能存在更短)。
一个可能的解决方案是将 `'a == 'b` 从函数调用一直持续到第一个闭合的 `}`。这符合上述所有约束条件(`long_lifetime` 实际上比 `'b` 存在更长,但由于生命周期仅作为边界而不是严格的规定,所以是允许的)。
<details>
<summary>英文:</summary>
Because lifetimes in function parameters are _bounds,_ not strict lifetimes. So when you call `f(short_lifetime, long_lifetime)`, the compiler tries to find lifetimes `'a` and `'b` such that:
- `short_lifetime` lives _at least_ as long as `'a` (_but it may live longer_),
- `long_lifetime` lives _at least_ as long as `'b` (_but it may live longer_),
- `'a` is at least as long as `'b` (but they may be equal),
- the returned value lives _at most_ as long as `'b` (but it may live shorter).
One possible solution is to take `'a == 'b` lasting from the function call to the first closing `}`. This fits all the above constraints (`long_lifetime` actually lives longer than `'b` but that's allowed since the lifetimes are only bounds and not strict).
</details>
# 答案2
**得分**: 1
`'a: 'b` 读作 `'a` *比* `'b` 寿命长。所以你示例中的寿命是颠倒的,`'a` 是长寿命,`'b` 是短寿命。代码编译通过,因为你可以随时将来自较长寿命的引用转换为较短寿命的引用(即在你的情况下将引用 `&'a` 转换为 `&'b`)。在[参考文档](https://doc.rust-lang.org/reference/trait-bounds.html#lifetime-bounds)中了解更多。
<details>
<summary>英文:</summary>
`'a: 'b` reads `'a` *outlives* `'b`. So the lifetimes in your example are reversed, `'a` is the long lifetime and `'b` is the short one. The code compiles, because you can always cast a reference from a longer lifetime to a shorter lifetime (i.e. cast a reference `&'a` to `&'b` in your case). Read more in the [reference](https://doc.rust-lang.org/reference/trait-bounds.html#lifetime-bounds)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论