πŸŽ“
World 5 Β· Build Your Own Things

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. πŸŽ“

The Big Idea A method is a function that lives inside a struct. You write methods in a special block called 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.” πŸͺž

Think of it like this… A plain function is like a stranger measuring your room with a tape measure. A method is like the room being able to say, "My area is 30!" all by itself.

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. πŸŽ‰

Ferris says: You can teach a struct as many skills as you like. Just add more functions inside the same impl block. πŸ¦€
Try this! Add a second method called 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. 🎯

You learned… A method is a function that lives inside an 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. πŸͺ„