In the below code the last statement in the main
function complains that the borrowing struct is dropped, however it seems like it should be possible to return the reference to the value as it is actually from the owned value which lives long enough.
Maybe there is an unhelpful elided lifetime but I can't seem to work out something that does what I'd want.
Does anyone have a solution for this?
type Value = u32;
struct Ret<'a>(&'a Value);
struct Owning {
value: Value,
}
struct Borrowing<'a> {
owned: &'a Owning,
}
trait Get {
fn get(&self) -> Ret;
}
impl Get for Owning {
fn get(&self) -> Ret {
Ret(&self.value)
}
}
impl<'a> Get for Borrowing<'a> {
fn get(&self) -> Ret<'a> {
self.owned.get()
}
}
fn main() {
let owning = Owning { value: 2 };
let value_from_owned = owning.get();
println!("{:?}", value_from_owned.0);
let owned_ref = &owning;
let value_from_owned_ref = owned_ref.get();
println!("{:?}", value_from_owned_ref.0);
let borrowed = Borrowing { owned: owned_ref};
let value_from_borrowed = borrowed.get();
println!("{:?}", value_from_borrowed.0);
let value_from_borrowed = Borrowing { owned: owned_ref }.get();
println!("{:?}", value_from_borrowed.0);
}