2013-06-25 24 views
17

Poruszam się z Rustem, przechodzę przez przykłady, próbuję stworzyć zajęcia. I zostały patrząc na example of StatusLineTextPrzedmioty i klasy w Rust

Utrzymuje podniesienie błędy:

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()); 
               ^~~~~~~~~ 

mojego kodu jest dość prosta:

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()); 
} 

Odpowiedz

21

Trzeba dodać wyraźnie self parametr aby methods:

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

Funkcje bez wcześniejszej niejawny parametr self jest uznawany za associated functions, który można wywołać bez określonej instancji.

+1

W celu wyjaśnienia, self musi być teraz jawnie zadeklarowane w parametrach metod, tak jak Rust 0.6 –