Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects and classes in Rust

Tags:

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()); } 
like image 420
RedMage Avatar asked Jun 25 '13 18:06

RedMage


People also ask

What are classes in Rust?

'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)

What is an object in Rust?

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.

What are objects and classes?

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.

Do we have classes in Rust?

In languages like C, Go, and Rust, classes are not a feature. Instead, these languages use structs, which define only a group of properties.


1 Answers

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.

like image 101
Lee Avatar answered Oct 12 '22 08:10

Lee