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()); }
'classes' act as factories for generating objects (often called instances) and define unique types. Classes may inherit from other classes (their parents), inheriting both data (fields) and behaviour (methods) If B inherits from A, then an instance of B can be passed to something expecting A (subtyping)
An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations. Under this definition, then, Rust is object-oriented: structs and enums have data and impl blocks provide methods on structs and enums.
A class is a user-defined type that describes what a certain type of object will look like. A class description consists of a declaration and a definition. Usually these pieces are split into separate files. An object is a single instance of a class. You can create many objects from the same class type.
In languages like C, Go, and Rust, classes are not a feature. Instead, these languages use structs, which define only a group of properties.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With