2016-11-15 20 views
1

我嘗試將解包的字符串引用發送給爲結構實現的靜態方法。下面是一個簡化代碼:對未解包屬性的引用失敗:使用部分移動的值:`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 
+0

參見http://stackoverflow.com/q/31233938/155423和[爲函數聲明'unwrap'(HTTPS:/ /doc.rust-lang.org/std/option/enum.Option.html#method.unwrap)。 – Shepmaster

+2

'as_ref()'在這裏可能比重複的建議更好,因爲您希望'&str'不是'&mut str'或'&mut String'。 – Aurora0001

+0

@ Aurora0001我試着添加'as_ref()',但它仍然不起作用(也許我誤解了一些東西)http://play.integer32.com/?gist=d6399128af86ae76f2b880dd711f7849&version=stable –

回答

4

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()) 
    } 
} 
+2

我認爲這可能更容易,只是把它全部在一行中,如[this](https://play.rust-lang.org/?gist=d0e5c2a66513613d5136deab406793d1&version=stable&backtrace=0)('Self :: b(self.p.as_ref()。unwrap()) ')以避免相當醜陋的塊。 – Aurora0001

+0

@ Aurora0001好點!該塊更多功能,所以很高興知道。 – Shepmaster

+0

@Shepmaster「代碼很奇怪」是的!這是因爲,只是簡單地展示我遇到的問題。不管怎樣,謝謝! –

相關問題