【发布时间】:2019-04-26 10:23:36
【问题描述】:
我的目标是返回对存储在 Box 中的特征对象的可变引用。
这似乎与question about borrowing references to optional struct members 有关,但主要区别似乎是特征对象的存在。 我也试图返回一个选项而不是一个结果。
尝试使用相同的方法似乎会导致终身问题。
示例代码:
trait Baz {}
#[derive(Debug)]
struct Foo;
impl Baz for Foo {}
struct Bar {
data: Option<Box<Baz>>,
}
enum BarErr {
Nope,
}
impl Bar {
fn borrow_mut(&mut self) -> Option<&mut Baz> {
self.data.as_mut().map(|x| &mut **x)
}
}
错误信息:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:20:9
|
20 | self.data.as_mut().map(|x| &mut **x)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
|
= note: expected type `std::option::Option<&mut dyn Baz>`
found type `std::option::Option<&mut (dyn Baz + 'static)>`
note: the anonymous lifetime #1 defined on the method body at 19:5...
--> src/lib.rs:19:5
|
19 | / fn borrow_mut(&mut self) -> Option<&mut Baz> {
20 | | self.data.as_mut().map(|x| &mut **x)
21 | | }
| |_____^
= note: ...does not necessarily outlive the static lifetime
我真的看不出寿命会在哪里延长。
同样尝试用as_mut 替换&mut **x 也无济于事。
【问题讨论】:
-
我在发布后不久就找到了一个可行的解决方案。但我很高兴接受一个对正在发生的事情有更好解释的答案。
-
请使用
rustfmt格式化您的代码。你可以在the playground右上角的工具下找到它。
标签: rust