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?