Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

rust - Extend lifetime of an object by taking a reference out of option

I'd like to define a struct representing a node in a graph, but in a way that it is possible to drop the reference later on. It would be easy with Box or Rc but I would prefer not to heap allocate this.

I believe that the problem can be abstracted to sth like that:

struct B<'a> {  
    b: Option<&'a B<'a>>,                                                  
}                                                                               
                                                                        
fn f() {                                                                 
    let mut b: B;
    {
        let a = B { b: None };
        b = B { b: Some(&a) };
        b.b.take();
    }
    b;
}

So this is perfectly fine for the var b to live in the outside block but compiler seems to be too restrictive here.

Any ideas how to solve this?

question from:https://stackoverflow.com/questions/65906258/extend-lifetime-of-an-object-by-taking-a-reference-out-of-option

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not the compiler being restrictive, when you declare

struct B<'a> {  
    b: Option<&'a B<'a>>,                                                  
}                                                                               

you are telling the compiler that B.b is going to live as long as B and what you want to do is tell the compiler that b has a lifetime of b and B as a lifetime of a.

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

struct Wrap<'a, 'b>{
    a: Option<&'a Foo>,
    b: Option<&'b Foo>,

}


fn main() {
    let mut w =  Wrap {
        a: None, 
        b: None,
    };
    w.b = Some(&Foo{b:0});
    {

        w.a = Some(&Foo{b: 1});
        w.a.take();

    }
    println!("b = {:?}", w.b);
}                                                                                                 

I don't know if this code will help but TLDR you have to specify a second lifetime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...