如何在结构中存储对象及其引用

时间:2019-03-28 02:33:29

标签: rust

我简化了代码,并制作了一个完整的版本,如下所示:

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板条箱...以及RefCell,但仍然不知道如何编译此代码。

1 个答案:

答案 0 :(得分:-1)

这样的自指结构是引入std::pin的确切原因。您可能需要检查文档中的this RFCthis example