Teaching Structs Tricks
In the last lesson we wrote a separate area function that took a rectangle. That
works great β but what if the rectangle could just know how to measure itself? Itβs
like teaching your dog to roll over: now that skill belongs to the dog! πΆ
In Rust, a skill that belongs to a struct is called a method. π
impl, and they use the word
&self to mean "this very rectangle."
The impl block
impl is short for implement β itβs where you teach your struct its skills. Inside
it, &self is how the method refers to the struct it belongs to.
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
Notice self.width instead of rect.width. The word self means βme, the rectangle
this method was called on.β πͺ
Calling a method
Once the skill is taught, you call it with a dot, just like reading a field β but with
parentheses on the end: rect.area().
See rug.area()? The rug measured itself. The method reached inside with
self.width and self.height and multiplied them to get 30. π
impl block. π¦
perimeter that returns
self.width + self.width + self.height + self.height, then print
rug.perimeter(). Run it and see the distance around the rug!
Quick quiz
What word does a method use to mean "this very struct"?
Yes! Methods use &self to talk about the struct they belong to. π―
impl block,
uses &self to mean the struct itself, and is called with a dot like
rect.area(). You can now build your own types and give them
their own skills! Next world: World 6 β Choices & Magic Sorting, where your
programs start making decisions and putting things in order. πͺ