引用解包属性失败:使用部分移动值:`self` [英] Reference to unwrapped property fails: use of partially moved value: `self`
本文介绍了引用解包属性失败:使用部分移动值:`self`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试将未包装的字符串引用发送到为结构实现的静电方法。以下是简化的代码:
fn main() {
let a = A {p: Some("p".to_string())};
a.a();
}
struct A {
p: Option<String>
}
impl A {
fn a(self) -> Self {
Self::b(&self.p.unwrap());
self
}
fn b(b: &str) {
print!("b: {}", b)
}
}
失败:
error[E0382]: use of partially moved value: `self`
--> src/main.rs:14:13
|
13 | Self::b(&self.p.unwrap());
| ------ value moved here
14 | self
| ^^^^ value used here after move
|
= note: move occurs because `self.p` has type `std::option::Option<std::string::String>`, which does not implement the `Copy` trait
我认为实现Copy
特征不是解决方案。如何在该上下文中解开p
并将其作为&str
传递给b
?
我按照Can't borrow File from &mut self (error msg: cannot move out of borrowed content)中的建议更改了代码:
fn main() {
let a = A {p: Some("p".to_string())};
a.a();
}
struct A {
p: Option<String>
}
impl A {
fn a(self) -> Self {
let c = self.p.as_ref().unwrap();
Self::b(&c);
self
}
fn b(b: &str) {
print!("b: {}", b)
}
}
这会导致不同的错误:
error[E0505]: cannot move out of `self` because it is borrowed
--> src/main.rs:15:13
|
13 | let c = self.p.as_ref().unwrap();
| ------ borrow of `self.p` occurs here
14 | Self::b(&c);
15 | self
| ^^^^ move out of `self` occurs here
推荐答案
如Can't borrow File from &mut self (error msg: cannot move out of borrowed content)中所述,您不能对借用值调用unwrap
,因为unwrap
取得该值的所有权。
as_ref
会借用值self
。当对值的任何引用都未完成时,不允许移动值(包括返回该值)。这意味着您需要将借用期限限制为在需要移动值之前结束:
fn a(self) -> Self {
{
let c = self.p.as_ref().unwrap();
Self::b(c);
}
self
}
它可能是示例中的工件,但是代码非常奇怪。我会写成
impl A {
fn a(self) -> Self {
self.b();
self
}
fn b(&self) {
print!("b: {}", self.p.as_ref().unwrap())
}
}
或
impl A {
fn a(&self) {
print!("a: {}", self.p.as_ref().unwrap())
}
}
这篇关于引用解包属性失败:使用部分移动值:`self`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文