Methods in Structs

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
		// We are implements area method for the Rectangle struct
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}
  • Everything within thisĀ implĀ block will be associated with theĀ RectangleĀ type
  • Methods must have a parameter namedĀ selfĀ of typeĀ SelfĀ for their first parameter.
  • Note that we still need to use theĀ &Ā in front of theĀ selfĀ shorthand to indicate that this method borrows theĀ SelfĀ instance
  • Methods can take ownership ofĀ self

Assosiated Functions

All functions defined within anĀ implĀ block are calledĀ associated functionsĀ because they’re associated with the type named after theĀ impl. We can define associated functions that don’t haveĀ selfĀ as their first parameter because they don’t need an instance of the type to work with.

impl Rectangle {
    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}

fn main() {
	let sq = Rectangle::square(3);
}