在“ get_trait_mut”中返回对特征的可变引用

时间:2019-02-26 21:53:21

标签: rust

请考虑以下内容:

pub trait Inner {}

pub struct Thing<'a> {
    inner: &'a Inner,
}

impl<'a> Thing<'a> {
    pub fn get_inner(&self) -> &Inner {
        self.inner
    }

    pub fn get_inner_mut(&mut self) -> &mut Inner {
        &mut self.inner
    }
}

导致:

error[E0277]: the trait bound `&'a (dyn Inner + 'a): Inner` is not satisfied
  --> src/lib.rs:13:9
   |
13 |         &mut self.inner
   |         -^^^^^^^^^^^^^^
   |         |
   |         the trait `Inner` is not implemented for `&'a (dyn Inner + 'a)`
   |         help: consider removing 1 leading `&`-references
   |
   = note: required for the cast to the object type `dyn Inner`

哪个比较公平,所以让我们听从建议吧?

与上述更改相同:

pub fn get_inner_mut(&mut self) -> &mut Inner {
    mut self.inner
}
error: expected expression, found keyword `mut`
  --> src/lib.rs:13:9
   |
13 |         mut self.inner
   |         ^^^ expected expression

(找到的关键字mut是我的本地编译器所说的,虽然不是下面的“游乐场”链接中的那个!)

嗯,有道理吧?单独mut并不是表达式

但是如何返回可变引用呢?

好的,让我们开始尝试一下吧?

pub fn get_inner_mut(&mut self) -> &mut &Inner {
    &mut &self.inner
}

(注意,更改了签名!)

导致:

error[E0308]: mismatched types
  --> src/lib.rs:13:9
   |
13 |         &mut &self.inner
   |         ^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected type `&mut &dyn Inner`
              found type `&mut &'a (dyn Inner + 'a)`
note: the anonymous lifetime #1 defined on the method body at 12:5...
  --> src/lib.rs:12:5
   |
12 | /     pub fn get_inner_mut(&mut self) -> &mut &Inner {
13 | |         &mut &self.inner
14 | |     }
   | |_____^
note: ...does not necessarily outlive the lifetime 'a as defined on the impl at 7:6
  --> src/lib.rs:7:6
   |
7  | impl<'a> Thing<'a> {
   |      ^^

仅指定生存期就可以解决所有问题吗?

这里是the playground

1 个答案:

答案 0 :(得分:2)

我看到的主要问题是Thing仅具有对inner不可变引用。

这是我的看法:

pub trait Inner {}

pub struct Thing<'a> {
    inner: &'a mut Inner,
}

impl<'a> Thing<'a> {
    pub fn get_inner(&self) -> &Inner {
        self.inner
    }

    pub fn get_inner_mut(&mut self) -> &mut Inner {
        &mut *self.inner
    }
}

struct SomeInner {}

impl Inner for SomeInner {}

fn main() {
    let mut inner = SomeInner {};
    let mut thing = Thing { inner: &mut inner };

    let inner: &Inner = thing.get_inner();
    let mutable_inner: &mut Inner = thing.get_inner_mut();
}

它会编译(您可以验证on the playground

注释

  • let mut inner = SomeInner {}-> inner可变
  • let mut thing-> thing也是可变的
  • &mut *self.shape->我正在取消引用,然后再次创建对其的可变引用

我确信还有更完善的解决方案,希望其他人也能提供帮助。

编辑:正如Shepmaster所指出的那样,根本不需要编写&mut *self.shape。由于我们已经可以访问可变引用,因此只需返回self.inner就足够了-编译器将确保遵循可变性。

最后,我的尝试将变成:

impl<'a> Thing<'a> {
   pub fn get_inner(&self) -> &Inner {
     self.inner
   }

   pub fn get_inner_mut(&mut self) -> &mut Inner {
      self.inner
   }
}

Full example on playground