Rust Book - Chapter 5

💡
These are my personal learning notes as I study

A struct [1] is similar to an Object's data attributes.

stuct Rectangle {
   width: u32,
   height: u32,
}

Methods

Methods are similar constructs to functions, except that they are defined in the context of a struct (or an enum or trait object), and their first parameter is always self, which represents the instance of the struct
the method is being called on.

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.area() > other.area()
    }

    fn area(&self) -> u32 {
        self.width * self.height
    }
}

A method will live inside of an impl block. By the way, a struct can have multiple impl blocks.

Associated functions

All functions defined within an impl block are called associated functions, because they're associated with the type of the struct. We can define associated functions that don't have self as their first parameter (thus aren't methods).


  1. data structure that lets you package together and name multiple related values that make up a meaningful group ↩︎