I've simplified the code and made a self-contained version of it as follows:
struct TakesRef<'a> {
string_ref: &'a str,
}
impl<'a> TakesRef<'a> {
fn new(string_ref: &'a str) -> TakesRef<'a> {
TakesRef { string_ref }
}
}
struct Wrapper<'a> {
string: String,
obj: TakesRef<'a>,
}
impl<'a> Wrapper<'a> {
fn new(string: String) -> Wrapper<'a> {
let obj = TakesRef::new(&string);
Wrapper { obj, string }
}
}
The error I get is:
error[E0515]: cannot return value referencing function parameter `string`
--> src/lib.rs:19:9
|
18 | let obj = TakesRef::new(&string);
| ------- `string` is borrowed here
19 | Wrapper { obj, string }
| ^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `string` because it is borrowed
--> src/lib.rs:19:24
|
16 | impl<'a> Wrapper<'a> {
| -- lifetime `'a` defined here
17 | fn new(string: String) -> Wrapper<'a> {
18 | let obj = TakesRef::new(&string);
| ------- borrow of `string` occurs here
19 | Wrapper { obj, string }
| ---------------^^^^^^--
| | |
| | move out of `string` occurs here
| returning this value requires that `string` is borrowed for `'a`
I can't change the definition of TakesRef
since it is a library class. How can I design Wrapper
to be able to store a TakesRef
inside? I tried using the owned-ref and rental crates... as well as RefCell
but I still can't figure out how to compile this code.