🧩
World 5 Β· Build Your Own Things

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.

The Big Idea A struct bundles related pieces of data into one neat package that you design. Each piece is called a field, and every field has a name and a type.

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! 🐢

Think of it like this… A struct is like a form with labeled blanks. The form says Name: ____ and Age: ____. Filling in the blanks makes one real 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. 🎯

Ferris says: You can create many dogs from the same kit. Make a second dog with a different name and age β€” same form, different answers. πŸ¦€
Try this! Change the name to your own pet (or a made-up one) and pick a new age. Press β–Ά Run to meet your new dog.

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. 🎯

You learned… A struct is your own custom type that bundles related fields together, you create an instance by filling in the blanks, and you read a field with a dot. Next up: building a Rectangle and measuring it! πŸ“