Git repo: https://github.com/caveofprogramming/rust/
Struct Methods
Rust allows us to attach methods to structs, using an impl
code block.
Here, &self
is a shortcut way of writing self: &Self
, and Self
is in turn an alias for the type the function is attached to; in this case, Person
.
This method can then be called via instances of Person using a dot notation.
Here I’ve defined a simple ‘get’ method, which Rust apparently has no special syntax for, but of course we can do whatever we want in a method.
We are also allowed to pass additional parameters to the method after the &self
parameter.
If we create a get method for the name field as well, in total we end up with this:
Associated Functions
Rust allows us to define methods which do not have a &self
parameter and so cannot access instance fields.
These are similar to class methods or static methods in other languages.
One use of this would be to add a method that returns an instance of the struct type.
Here I’ve added an associated function called new
(which has no special meaning in Rust) which returns a new instance of Person
.
In place of Self
we could equally well use Person
, if desired. It’s the same.
We can run this method via the type name of the struct and a :: syntax.