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/

相关文章:

xml - 如何从不在重复项中使用结束标记的嵌套 xml 中获取数据?

rust - 手动删除引用包装器的Rust生命周期问题

reference - 如何为对结构的引用实现 Add 特性?

c - 如何正确地将内存分配给存储在结构中的动态整数数组?

arrays - 如何在 Swift 中打印结构的某些元素?

c - 在具有灵活数组的结构的初始化中使用 sizeof 运算符

rust - 您可以存储可用于访问 AnyMap 的任意类型吗?

rust - 如何通过Rust中的Unix套接字发送和收听数据?

rust - 在 Rust 中调试堆栈溢出是否有任何标准方法?

c - 我在函数中分配内存,并返回 char*,我应该如何释放它?