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

Example: A Rectangle

Time to build something useful with a struct! Let’s make a Rectangle β€” like a door, a phone screen, or a chocolate bar. Every rectangle has a width and a height, and once we know those two numbers, we can figure out its area (how much space it covers). πŸ“

The Big Idea The area of a rectangle is just width * height. If we bundle width and height into a struct, we can hand the whole rectangle to a function and let it do the math.

Our Rectangle kit

struct Rectangle {
    width: u32,
    height: u32,
}

Two fields, both whole numbers (u32). Now we need a helper that takes a rectangle and gives back its area. We’ll borrow the rectangle with an &, which means β€œlet me look at it without taking it away.” πŸ‘€

Measuring the space

A rectangle that is 5 wide and 6 tall covers 5 Γ— 6 = 30 little squares. The function reached into the struct with rect.width and rect.height and multiplied them. πŸŽ‰

Think of it like this… Picture a chocolate bar with 5 chunks across and 6 rows down. Count all the chunks: 30! That's the area. 🍫

A peek inside with Debug

Sometimes you want to print the whole struct at once to peek inside it. Add #[derive(Debug)] above the struct, then print it with {:?}.

The {:?} is like asking Rust to β€œshow me everything inside this box.” πŸ“¦

Ferris says: derive(Debug) is a free feature Rust gives you so you can peek inside your structs while building. Really handy. πŸ¦€
Try this! Change the width to 10 and the height to 4 in the first playground. What area do you get? Run it and check!

Quick quiz

A Rectangle has width: 7 and height: 2. What is its area?

Right! Area is width times height, and 7 Γ— 2 = 14. πŸŽ‰

You learned… You can build a Rectangle struct, write a function that borrows it with & to compute the area, and use #[derive(Debug)] with {:?} to peek inside. Next up: teaching your structs cool tricks called methods! πŸŽ“