Rust methods

From wikinotes
Revision as of 20:28, 7 February 2023 by Will (talk | contribs)

Rust lets you add methods to structs and enums.

TODO:

other types? what's the full spectrum here?

Associated Functions

Rust lets you add methods to structs/enums using impl.

  • self is a reference to the instance
  • Self is a reference to the object-type
  • impl allows you to associate functions to an object
  • you can have as many impl blocks as you'd like
type RgbColor{
    r: u8,
    g: u8,
    b: u8,
}

impl RgbColor {
    // ~static-method
    fn red() -> Self {
        Self {
            r: 255,
            g: 0,
            b: 0,
        }
    }

    // method
    fn brighten(&self) {
        self.r += 8;
        self.g += 8;
        self.b += 8;
    }
}

// methods
let c = RgbColor{r: 8, g: 8, b: 8};
c.brighen();  // {r: 16, g: 16, b: 16}

// class methods
red = RgbColor::red()

Similar to go, you can use the . operator to access methods on either a reference or an instance.
rust will automatically dereference it for you.