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

标签 struct rust lifetime

代码如下:

#[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/

相关文章:

c# - 编码结构数组指针的最佳方法

swift - 将结构数组分配给协议(protocol)数组

rust - 在一个表达式中两次借用 self 有时会导致错误

rust - Blanket impl、HRTB 和 "impl"抽象返回类型 : "expected bound lifetime parameter"

parsing - nom 解析一个单独的列表

c++ - 临时对象的生命周期 : iterator to temporary vector in nested function call

mysql - 如何检查MySQL缓存生命周期?

c - 程序跳过用户输入(C 语言的大型模块化图书馆信息系统)

c++ - 在 C 中使 struct fields const

GIT 存储说明