2013-06-25 60 views
17

我在擺弄Rust,試着做例子,試着做一個課。我一直在尋找的example of StatusLineTextRust中的對象和類

它不斷提高的錯誤:

error: `self` is not available in a static method. Maybe a `self` argument is missing? [E0424] 
      self.id + self.extra 
      ^~~~ 

error: no method named `get_total` found for type `main::Thing` in the current scope 
    println!("the thing's total is {}", my_thing.get_total()); 
               ^~~~~~~~~ 

我的代碼是相當簡單:

fn main() { 
    struct Thing { 
     id: i8, 
     extra: i8, 
    } 

    impl Thing { 
     pub fn new() -> Thing { 
      Thing { id: 3, extra: 2 } 
     } 
     pub fn get_total() -> i8 { 
      self.id + self.extra 
     } 
    } 

    let my_thing = Thing::new(); 
    println!("the thing's total is {}", my_thing.get_total()); 
} 

回答

21

您需要添加一個明確的self參數,使methods

fn get_total(&self) -> i8 { 
    self.id + self.extra 
} 

沒有ex的函數暗self參數被認爲是associated functions,可以在沒有特定實例的情況下調用該參數。

+1

爲了澄清,現在必須在方法的參數中明確地聲明自Rust 0.6 – 2013-06-26 18:29:21