I've hit another ownership issue, but I'm sure it's just me not considering something. I'd like for some borrowed memory to "hitch a ride" with its owned source, and return from a function together. Say, in a struct like this:
struct Foo<'a> {
borrowed: Vec<&'a str>,
owned: Vec<String>,
}
Something is already fishy about that 'a
, since there's nothing about it that guarantees the borrow is coming from the String
s in the next field. Yet that's precisely what I'm attempting:
fn foo<'a>() -> Foo<'a> {
let owned: Vec<String> = vec!["hello".to_owned(), "there".to_owned()];
let borrowed = owned.iter().map(|s| s.as_str()).collect();
Foo { borrowed, owned }
}
It was initially a surprise to me that this doesn't compile. We see:
|
404 | let borrowed = owned.iter().map(|s| s.as_str()).collect();
| ----- `owned` is borrowed here
405 |
406 | Foo { borrowed, owned }
| ^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
Surely you jest, Rust. Clearly owned
is moved out too, and my foo
function no longer owns it. I'll add that due to the 'a
('static
doesn't help), we also see:
406 | Foo { borrowed, owned }
| ----------------^^^^^--
| | |
| | move out of `owned` occurs here
| returning this value requires that `owned` is borrowed for `'a`
The 'a
from outside is stange, but it's the only thing I can think to do. The Foo
demands some explicit lifetime, and with that there, the foo
function complains if I try to leave anything out.
How do I let my borrowed data "hitch a ride" with its original owned source?