我已经简化了代码并制作了一个独立的版本,如下所示:
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 }
}
}
我得到的错误是:
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`
我无法更改的定义,TakesRef
因为它是一个库类。我怎样才能设计Wrapper
能够存储TakesRef
内部?我尝试使用owned-ref 和rental crates ......以及,RefCell
但我仍然无法弄清楚如何编译这段代码。