Methods on structs
All the functions defined for our struct
until now are so called associated functions, they are associated with the struct
and are called with the syntax:
Struct_name::ass_function()
We can also define real methods in Rust, that are called on a struct
instance and that have a reference to that instance &self
as first parameter.
When a specific struct Alien
attacks, we can define a method for that Alien
struct like this:
fn attack(&self) { println!("I attack! Your health lowers with {} damage points.", self.damage); }
And call it on the function alien berserk
as follows:
berserk.attack();
A reference to berserk
object (the Alien
object on which the method is invoked) is passed as &self
to the method. In fact the self
object is like the self
object in Python or this
in Java or C#. A method always has &self
instance as a parameter, in contrast to a static method.
Here the object is passed immutably, but what if attacking also lowers the Alien
structs own...