请考虑以下内容:
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> {
| ^^
仅指定生存期就可以解决所有问题吗?
答案 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
}
}