Returning a value with a reference to a local variable

I want to write more or less this code:

struct Foo<'a> {
  bar: &'a str,
}

fn get_a_foo() -> (Foo, String) {
    let bar = "bar".to_owned();
    (Foo{ bar: &bar }, bar)
}

I understand enough about the Rust ownership / moves to understand why the code as written can't work. In theory, I should be able to box bar so that the string's address doesn't move when the value is moved out of the function. This smells like Pin to me, but I don't understand that API well enough to leverage it effectively. Is there a way to get something like this to work?

As additional context, I don't own Foo, so making it own it's dependencies isn't really an option. For now, I'm just duplicating a bunch of code, but it would be nice if there were a way to return an opaque struct that can own Foo's dependencies.

Apologies for the duplicate question. In case someone else comes across this, it seems that the owning_ref crate is what I need.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.