简体   繁体   English

结构必须超过成员引用

[英]Struct must outlive member reference

I'm not sure how to properly title this post. 我不确定如何正确地为此帖子加上标题。 I'm fairly new to Rust and trying to compile a program following this simple structure, but it seems to be incorrect, and I'm not sure why. 我对Rust还是很陌生,并尝试按照这种简单的结构编译程序,但这似乎是不正确的,而且我不确定为什么。

struct Bar;

impl Bar {
    fn do_thing(&self) { println!("Ha, do nothing!") }
}

struct Foo<'a> {
    bar: &'a Bar
}

impl<'a> Foo<'a> {
    fn new(b: &Bar) -> Foo { Foo { bar: b } }
    fn get_bar(&self) -> &Bar { self.bar }
}

fn main() {
    let b = Bar;
    let b_ref = {
        let f = Foo::new(&b);
        f.get_bar()
    };
    b_ref.do_thing();
}

The compiler error here claims that f does not live long enough. 此处的编译器错误声称f寿命不足。 It shouldn't matter how long f lives though -- b_ref is valid for as long as b is, and I thought that references were Copy so that we wouldn't have to worry about the actual reference in f . 不过, f生存时间b_ref的有效期与b一样长,而且我认为引用是Copy因此我们不必担心f的实际引用。 Is this relevant? 这相关吗?

Part of me feels like I need to specify the lifetime of the &Bar being returned from get_bar , but I don't know how to tie that into the lifetime of the Foo struct? 我的一部分感觉是我需要指定从get_bar返回的&Bar的生存期,但是我不知道如何将其与Foo结构的生存期联系起来?

What am I missing here? 我在这里想念什么?

You have to specify that the reference you are returning is tied to the lifetime 'a and not the lifetime of self that compiler will infer for you: 您必须指定要返回的引用与生命周期'a ,而不与编译器将为您推断的self的生命周期相关:

impl<'a> Foo<'a> {
    fn new(b: &Bar) -> Foo { Foo { bar: b } }
    fn get_bar(&self) -> &'a Bar { self.bar }
}

This is equivalent to the original code: 这等效于原始代码:

impl<'a> Foo<'a> {
    fn new(b: &Bar) -> Foo { Foo { bar: b } }
    fn get_bar<'b>(&'b self) -> &'b Bar { self.bar }
}

Part of me feel like I should need to specify the lifetime of the &Bar being returned from get_bar, but I don't know how to tie that into the lifetime of the Foo struct? 我的一部分感到应该指定从get_bar返回的&Bar的生存期,但是我不知道如何将其与Foo结构的生存期联系起来?

The lifetime of Foo does not matter at all in this case. 在这种情况下, Foo的寿命根本不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM