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). π
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. π
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.β π¦
derive(Debug) is a free feature Rust gives
you so you can peek inside your structs while building. Really handy. π¦
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. π
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! π