How can I fix the code below? I tried using owning_ref
but I can't get it to work.
extern crate owning_ref; // 0.4.0
struct ExternalAPIStruct<'a> {
inner: &'a str,
}
impl<'a> ExternalAPIStruct<'a> {
pub fn new(config: &'a str) -> Self {
ExternalAPIStruct { inner: config }
}
}
// can be changed
struct MyStruct<'a> {
ext: ExternalAPIStruct<'a>,
}
impl<'a> MyStruct<'a> {
pub fn new(config: String) -> Self {
// can be changed
MyStruct {
// can't reference a local variable
ext: ExternalAPIStruct::new(&config)
}
}
}
fn main() {
let dynamic_str = "Hello there".to_owned();
let _my_struct = MyStruct::new(dynamic_str);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing function parameter `config`
--> src/main.rs:21:9
|
21 | / MyStruct {
22 | | ext: ExternalAPIStruct::new(&config)
| | ------- `config` is borrowed here
23 | | }
| |_________^ returns a value referencing data owned by the current function
error: aborting due to previous error
For more information about this error, try `rustc --explain E0515`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.
UPD:
Worked around with an owning_ref::OwningHandle
(unfortunately, it uses unsafe
):