gpt4 book ai didi

struct - 结构的所有字段的相同生命周期参数

转载 作者:行者123 更新时间:2023-11-29 08:36:16 24 4
gpt4 key购买 nike

代码如下:

#[derive(Debug)]
struct Foo {
f: i32,
}

#[derive(Debug)]
struct Bar<'a> {
bar1: &'a Foo,
bar2: &'a Foo,
}

#[allow(unused_variables)]
fn make_bar<'a>(foo1: &'a Foo, foo2: &'a Foo) -> Bar<'a> {
Bar {
bar1: foo1,
bar2: foo2,
}
}

fn extract_bar2<'a>(foo: &'a Foo) -> &'a Foo {
let foo1 = Foo { f: 22 };
let foo2 = make_bar(&foo, &foo1).bar1;
foo2
}

fn main() {
let foo = Foo { f: 11 };
let foo1 = extract_bar2(&foo);
println!("foo1: {:?}", foo1);
}

这给出了一个错误:

error: `foo1` does not live long enough
--> src/main.rs:23:32
|>
23 |> let foo2 = make_bar(&foo, &foo1).bar1;
|> ^^^^
note: reference must be valid for the lifetime 'a as defined on the block at 21:45...
--> src/main.rs:21:46
|>
21 |> fn extract_bar2<'a>(foo: &'a Foo) -> &'a Foo {
|> ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 22:29
--> src/main.rs:22:30
|>
22 |> let foo1 = Foo { f: 22 };
|> ^

核心问题是:在结构的上下文中,生命周期参数实际上意味着什么?

更具体地说:结构的所有字段具有相同生命周期参数的后果是什么?他们的生命周期必须完全一样吗?他们必须重叠吗?如果是这样,它们应该重叠到什么程度?

以下两个结构之间的(语义和实际)差异是什么?

struct Bar<'b> {
bar1: &'b Foo,
bar2: &'b Foo,
}
struct Bar<'a, 'b> {
bar1: &'a Foo,
bar2: &'b Foo,
}

最佳答案

What are the (semantic and practical) differences between the following two structs?

有一个小例子来说明区别:

#[derive(Debug)]
struct Foo;

#[derive(Debug)]
struct Bar1<'b> {
foo1: &'b Foo,
foo2: &'b Foo,
}

#[derive(Debug)]
struct Bar2<'a, 'b> {
foo1: &'a Foo,
foo2: &'b Foo,
}

fn main() {//'a -->
let foo1 = Foo;
let ref_foo1 =
{//'b -->
let foo2 = Foo;
//error: `foo2` does not live long enough
//replace the Bar1 with Bar2 in the row below to fix error
let bar = Bar1{foo1:&foo1, foo2:&foo2};
bar.foo1
};//--> 'b
println!("ref_foo1={:?}", ref_foo1);
}//--> 'a

Bar1 将其成员的生命周期截断到它们的交集。因此,您无法从 Bar1 结构中获取对生命周期为 'afoo1 的引用。您将获得生命周期 'b 的引用。

我应该注意,这种情况下的错误信息有点误导

关于struct - 结构的所有字段的相同生命周期参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39495717/

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