gpt4 book ai didi

reference - 从作为参数传递给函数的引用返回内部引用时的生命周期处理

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

尽管生命周期 'a'b 彼此独立,但以下代码编译正常的原因是什么?

struct Foo<'a> {
i: &'a i32
}

fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}

fn main() {}

如果我使 Foo 中的引用 i 可变,它会给出以下错误。

5 | fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
| ----------- -------
| |
| this parameter and the return type are declared with different lifetimes...
6 | x.i
| ^^^ ...but data from `x` is returned here

出现上述错误的原因是什么?它是否认为它是可变引用的所有权并且它看到某些东西(来自 Foo)正在被取出(具有独立的生命周期),这是不可能的,因此错误?

这段代码(我认为会通过)也失败了:

struct Foo<'a> {
i: &'a mut i32
}

fn func<'a, 'b: 'a>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}

fn main() {}

因错误而失败:

 error[E0623]: lifetime mismatch
--> src/main.rs:6:5
|
5 | fn func<'a, 'b: 'a>(x: &'a Foo<'b>) -> &'b i32 {
| -----------
| |
| these two types are declared with different lifetimes...
6 | x.i
| ^^^ ...but data from `x` flows into `x` here

但是这个通过了:

struct Foo<'a> {
i: &'a mut i32
}

fn func<'a: 'b, 'b>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}

fn main() {}

这对我来说似乎有点违反直觉。在这里,外部生命周期 ('a) 可能比内部生命周期 ('b) 长。为什么这不是错误?

最佳答案

What is the reason the following code compiles fine, despite both the lifetimes 'a and 'b being independent of each other?

fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}

原因是它们彼此独立。

类型&'a Foo<'b>如果 'a 是不可能的已过期 'b .因此,Rust 借用检查器隐含地推断您必须打算 'b: 'a ( 'b'a 长)。所以上面的代码在语义上与此相同:

fn func<'a, 'b: 'a>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}

If I make the reference i in Foo mutable, it gives the following error.

5 | fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
| ----------- -------
| |
| this parameter and the return type are declared with different lifetimes...
6 | x.i
| ^^^ ...but data from `x` is returned here

What is the reason it gives the above error?

当您传递一个不可变 引用时,它会被复制。在上面的示例中,这意味着 &'b i32可以自行移动,它的活跃度与你从哪里得到它无关。这个复制的引用总是指向数据的原始地址。这就是第一个示例有效的原因 - 即使 x被删除,原始引用仍然有效。

当您传递一个可变 引用时,它会移动。这种情况的结果是引用仍然“通过”变量 x .如果不是这种情况,xFoo 内容的可变引用可以与这个新的不可变引用同时存在——这是不允许的。因此,在这种情况下,引用不能超过 'a。 - 或者换句话说:'a: 'b .

但我们不是已经说过'b: 'a了吗? ?这里唯一的结论是 'a'b必须是相同的生命周期,这是您之前的错误消息所要求的。

关于reference - 从作为参数传递给函数的引用返回内部引用时的生命周期处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239075/

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