Um momento
0x50Lesson 6 of 6

Model domain data with structs and enums

Build custom types and represent state clearly.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • 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.

main.rs
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}
Output
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.

Exercise 1

Describe a rectangle area

+25 XP

Create a Rectangle struct with width and height fields and print area (width * height) from stdin values.

  • Three by four
  • Five by two
main.rs
Loading editor…

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…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: