RedMage
RedMage

Reputation: 1116

Objects and classes in Rust

I am fiddling around with Rust, going by the examples, trying to make a class. I have been looking at the example of StatusLineText

It keeps raising the errors:

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

My code is rather simple:

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

Upvotes: 28

Views: 21468

Answers (1)

Lee
Lee

Reputation: 144206

You need to add an explicit self parameter to make methods:

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

Functions without the explicit self parameter are considered associated functions, which can be called without a specific instance.

Upvotes: 30

Related Questions