Enums for Custom Types
Utilize enums to define types that can be one of several variants, often carrying associated data.
Enums for Custom Types is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Enums: Custom Type Choices
Welcome to Enums for Custom Types! In Rust, enums (enumerations) let you define a type that can be one of several possible, distinct variants.
Think of an enum as a way to say, "This item can be A, OR B, OR C." It's incredibly useful for representing different states or choices.
Defining a Simple Enum
To define an enum, you use the enum keyword followed by its name and curly braces containing its variants. Each variant is a distinct choice.
Here's a simple example for cardinal directions:
enum Direction {
North,
South,
East,
West,
}
fn main() {
let my_direction = Direction::North;
println!("My direction is {:?}", my_direction);
}Enums with Associated Data
Unlike simple variants, enum variants can also hold data! This makes enums very powerful, as each variant can carry its own distinct set of information.
The data can be a tuple (like (i32, String)) or a struct (like { x: i32, y: i32 }).
Associated Data in Action
Let's see an enum where each variant represents a different type of message, some carrying data and some not.
Notice how Move uses a struct, Write uses a String, and ChangeColor uses a tuple.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let m1 = Message::Quit;
let m2 = Message::Move { x: 10, y: 20 };
let m3 = Message::Write(String::from("hello"));
let m4 = Message::ChangeColor(255, 0, 128);
// We can't directly print enums with associated data using {:?}
// without deriving Debug, which we'll cover later.
// For now, just know these instances are created.
println!("Messages created!");
}The `Option` Enum: Handling Absence
One of Rust's most fundamental enums is Option<T>. It's used to represent values that might or might not exist, preventing null pointer errors common in other languages.
Some(T): The variant that holds a value of typeT.None: The variant that represents no value.
Using `Option<T>` Effectively
Option<T> forces you to explicitly handle both the Some and None cases, making your code safer and more robust. No more unexpected null crashes!
Here's how you might use it:
fn find_item(id: i32) -> Option<String> {
if id == 7 {
Some(String::from("Found item 7!"))
} else {
None
}
}
fn main() {
let item1 = find_item(7);
let item2 = find_item(5);
println!("Item 1: {:?}", item1);
println!("Item 2: {:?}", item2);
}Briefly: The `Result` Enum
Another vital enum is Result<T, E>, used for error handling. It has two variants:
Ok(T): Indicates success and contains the successful value.Err(E): Indicates failure and contains an error value.
We'll dive deep into Result in a later lesson, but it's good to know it's another powerful enum pattern!
Methods on Enums
Just like structs, you can define methods for enums using an impl block. These methods can perform actions or return values based on the enum's variant.
Let's add a call method to our Message enum from before:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn call(&self) {
println!("A message was called!");
}
}
fn main() {
let m = Message::Write(String::from("hello"));
m.call();
}Quick Check on Enums
Which of the following statements are true about Rust enums?
Recap: Enums for Custom Types
Great job! You've learned how Rust enums provide a powerful way to define custom types that can be one of several variants.
- Enums allow you to model choices and states clearly.
- Variants can carry associated data, making them highly flexible.
- The
Option<T>enum is key for handling the absence of a value safely. - Enums can have methods defined with
implblocks.
Next, we'll explore how to work with these enum variants using powerful pattern matching!
Frequently asked questions
Is the “Enums for Custom Types” lesson free?
Yes — the full text of “Enums for Custom Types” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Enums for Custom Types”?
Utilize enums to define types that can be one of several variants, often carrying associated data. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Enums for Custom Types” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Defining and Using Structs
- Enums for Custom Types
- Powerful Pattern Matching