【发布时间】:2019-02-25 08:28:05
【问题描述】:
我有一段非常简单的代码无法编译:
struct X;
struct A {
field: Option<Box<X>>,
}
impl A {
pub fn get_field(&self) -> Option<&X> {
return self.field.map(|value| &*value);
}
}
error[E0507]: cannot move out of borrowed content
--> src/lib.rs:9:16
|
9 | return self.field.map(|value| &*value);
| ^^^^ cannot move out of borrowed content
error[E0597]: `*value` does not live long enough
--> src/lib.rs:9:40
|
9 | return self.field.map(|value| &*value);
| ^^^^^-
| | |
| | borrowed value only lives until here
| borrowed value does not live long enough
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 8:5...
--> src/lib.rs:8:5
|
8 | / pub fn get_field(&self) -> Option<&X> {
9 | | return self.field.map(|value| &*value);
10| | }
| |_____^
我真的不明白为什么这不起作用。
【问题讨论】:
-
self.field.as_ref().map(Box::as_ref);或return self.field.as_ref().map(|value| value.as_ref()); -
感谢@TimDiekmann,这是完美的
标签: rust