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