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); }