Methods

Methods are defined within the context of a struct (or enum) and either refer to the type or mutate it.

The first parameter of a method is always self, which represents the instance of the type the method is being called on.

Declaration

In this example we will take a look at a struct however an enum will work in the same way.

struct Foo {
    bar: u64,
}

We start by using the impl (implementation) keyword, followed by the name of our struct, to define a function that belongs to our object i.e. a method.

impl Foo {
    // refer to `bar`
    fn add_number(self, number: u64) -> u64 {
        self.bar + number
    }

    // mutate `bar`
    fn increment(ref mut self, number: u64) {
        self.bar += number;
    }
}

Usage

To call a method use the dot syntax: <variable name>.<method name>().

    let mut foo = Foo { bar: 42 };
    let result = foo.add_number(5); // evaluates to `47`
    foo.increment(5); // `bar` inside `foo` has been changed from 42 to 47