Model domain data with structs and enums
Build custom types and represent state clearly.
- Define and use a struct and an enum in practical code.
Structs group related fields under one named type. Enums model values that can be one of several variants. Together they help represent domain concepts clearly and safely, especially when combined with match.
1#[derive(Debug)]
2enum Status {
3 Todo,
4 Done,
5}
6
7#[derive(Debug)]
8struct Task {
9 title: String,
10 status: Status,
11}
12
13fn main() {
14 let task = Task { title: "Practice Rust".to_string(), status: Status::Todo };
15 println!("{:?}", task);
16}Task { title: "Practice Rust", status: Todo }Enums are more expressive than ad-hoc strings for states because the compiler checks valid variants. Pattern matching over enums avoids impossible or forgotten states.
Key takeaways
Define and use a struct and an enum in practical code.
Rust uses types and ownership rules to prevent common bugs.
Small experiments build intuition quickly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Rust
These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.
Describe a rectangle area
Create a Rectangle struct with width and height fields and print area (width * height) from stdin values.
- Three by four
- Five by two
Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…