Structs: Your Own LEGO Kits
Imagine you open a LEGO box and instead of random bricks, you get a neat tray with labeled spots: one for wheels, one for windows, one for doors. Everything you need for one cool thing, bundled together. In Rust, that labeled tray is called a struct! π§©
A struct lets you build your own custom type by grouping a few pieces of information that belong together.
Designing your kit
Letβs make a Dog struct. A dog has a name and an age, so those become our fields:
struct Dog {
name: String,
age: u8,
}
The name field holds text (a String), and age holds a small whole number (a
u8). We just designed a brand-new type called Dog! πΆ
Filling in the blanks
Making a real dog from the form is called creating an instance. To read a field,
you use a dot, like my_dog.name.
See how my_dog.name reaches into the package and grabs the name? The dot is like
pointing at one blank on the form. π―
Quick quiz
How do you read the name field of a dog called my_dog?
Yes! Use a dot to reach into a struct and grab one of its fields. π―
Rectangle and measuring it! π