2015-11-15 34 views
1

這裏是我的所有代碼:不能借用``爲永恆不變的,因爲`* self`也借爲可變[E0502]

use std::collections::HashMap; 

pub struct Book<'a> { 
    page: Vec<&'a str>, 
    histories: HashMap<&'a str, &'a str>, 
} 

impl<'a> Book<'a> { 
    pub fn new(page: Vec<&'a str>) -> Book<'a> { 
     let histories = HashMap::new(); 
     Book { 
      page: page, 
      histories: histories 
     } 
    } 

    pub fn process(&mut self, line: &str, book_id: &'a str) { 

     let page_c = self.get_page(book_id); 
     println!("page_c {}", page_c); 

     for history in self.histories.iter() { 
      println!("histories..."); 
     } 
    } 

    fn get_page(&mut self, book_id: &'a str) -> &str { 
     if !self.histories.contains_key(book_id) { 
      println!("not history found for book {}", book_id); 
      self.histories.insert(book_id, "history A"); 
     } 
     self.histories.get(book_id).unwrap() 
    } 
} 

fn main() { 
    println!("Hello, world!"); 
    let mut pages = Vec::new(); 
    let st = "page1"; 
    pages.push(st); 

    let mut biblio = Book::new(pages); 

    let sentence = "this is a line of page"; 
    let book_id = "onebook"; 
    biblio.process(sentence, book_id); 
} 

這並不編譯:

src/main.rs:22:24: 22:38 error: cannot borrow `self.histories` as immutable because `*self` is also borrowed as mutable [E0502] 
src/main.rs:22   for history in self.histories.iter() { 
             ^~~~~~~~~~~~~~ 
src/main.rs:19:22: 19:26 note: previous borrow of `*self` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*self` until the borrow ends 
src/main.rs:19   let page_c = self.get_page(book_id); 
            ^~~~ 
src/main.rs:25:6: 25:6 note: previous borrow ends here 
src/main.rs:17  pub fn process(&mut self, line: &str, book_id: &'a str) { 
... 
src/main.rs:25  } 
       ^
error: aborting due to previous error 
Could not compile `tempo`. 

我瞭解錯誤信息,但經過研究和閱讀similar questions,我不明白我如何修復我的代碼。

+2

Stack Overflow是不是代碼 - 撰寫(或修復)服務。既然你聲明你瞭解錯誤信息並且發現了類似的問題,你能不能給我們提供關於如何幫助你理解問題的指導*而不用爲你寫解決方案*?關於上一個問題和答案的不足之處是什麼? – Shepmaster

+2

也有很多問題要求同樣的事情。基本上所有在側邊欄中的「相關」Q&A都應該被檢出。 – Shepmaster

回答

1

解決您的代碼最簡單的方法是不引入了page_c一個額外的變量,但是從get_page直接使用結果:

pub fn process(&mut self, line: &str, book_id: &'a str) { 
    println!("page_c {}", self.get_page(book_id)); 

    for history in self.histories.iter() { 
     println!("histories..."); 
    } 
} 

這樣,當你到了forself不是借來的循環,因爲它只是借用println的電話。如果你確實想有page_c一個變量,你可以在一個額外的範圍介紹它,所以借將範圍的結束(因此在循環之前):

pub fn process(&mut self, line: &str, book_id: &'a str) { 
    { 
     let page_c = self.get_page(book_id); 
     println!("page_c {}", page_c); 
    } // page_c ceases to exist here, so the borrow of self ends 
    for history in self.histories.iter() { 
     println!("histories..."); 
    } 
} 
+0

感謝您的回答。我需要在循環之後使用''page_c'',類似於: ''} //循環結束 println!(「page_c {}」,page_c); }'' – Olivier

相關問題