gpt4 book ai didi

rust - 返回对 "get_trait_mut"中特征的可变引用

转载 作者:行者123 更新时间:2023-11-29 08:26:37 25 4
gpt4 key购买 nike

考虑以下几点:

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 是我本地编译器所说的,而不是下面 playground 链接中的那个!)

嗯,有道理,对吧? 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

最佳答案

我看到的主要问题是 Thing 只有对 innerimmutable 引用。

这是我的看法:

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

关于rust - 返回对 "get_trait_mut"中特征的可变引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54894735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com