我嘗試將解包的字符串引用發送給爲結構實現的靜態方法。下面是一個簡化代碼:對未解包屬性的引用失敗:使用部分移動的值:`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
參見http://stackoverflow.com/q/31233938/155423和[爲函數聲明'unwrap'(HTTPS:/ /doc.rust-lang.org/std/option/enum.Option.html#method.unwrap)。 – Shepmaster
'as_ref()'在這裏可能比重複的建議更好,因爲您希望'&str'不是'&mut str'或'&mut String'。 – Aurora0001
@ Aurora0001我試着添加'as_ref()',但它仍然不起作用(也許我誤解了一些東西)http://play.integer32.com/?gist=d6399128af86ae76f2b880dd711f7849&version=stable –