How to return a reference to an object created conditionally in Rust?

Viewed 47

I have a fairly rookie Rust question, but I can't figure it out. In short, I have a situation where I want to return a struct instance from a conditional block, but the struct contains a reference to an object that also gets created in that block. For example, something like:

struct Foo<'a> {
    num: &'a u8,
}

let fooOpt = if true {
    let num = 4;
    Some(Foo {
        num: &num,
    })
} else {
    None
};

This doesn't work, because the returned Foo contains a reference to num, which is dropped at the end of the if block. What is the right way to do this? I tried some hijinks with the struct taking ownership of num (in the real code it's an object instead of a u8, and the reference is to something inside the object), but structs containing references to data owned by themselves is surprisingly hard. Is there some simple way to do this that I'm just missing?

1 Answers

Self Referential structs are very hard. If you aren't sure you have to use them, you don't. In your case, if you can declare the objects outside the conditional, that would be ideal.

struct Foo<'a> {
    num: &'a u8,
}
let num = 4;
let fooOpt = if true {
    Some(Foo {
        num: &num,
    })
} else {
    None
};

I understand that this is probably a smaller example. If the object is very big or time consuming to create, then you can just declare it and leave the construction for later.

struct Foo<'a> {
    num: &'a u8,
}
let num;
let fooOpt = if true {
    num = 4;
    Some(Foo {
        num: &num,
    })
} else {
    None
};

This will only initialise the num variable when it is used, but the variable itself would be in the outer scope and thus, borrowing it would be fine.

Related