Enumerações para Tipos Personalizados
Utilize enumerações para definir tipos que podem assumir uma de várias variantes, frequentemente contendo dados associados.
Enumerações para Tipos Personalizados é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 3 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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!
Perguntas Frequentes
A aula “Enumerações para Tipos Personalizados” é grátis?
Sim — o texto completo de “Enumerações para Tipos Personalizados” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 3 aulas no total.
O que vou aprender em “Enumerações para Tipos Personalizados”?
Utilize enumerações para definir tipos que podem assumir uma de várias variantes, frequentemente contendo dados associados. Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 3.
Quanto tempo leva a aula “Enumerações para Tipos Personalizados”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Definição e Utilização de Estruturas
- Enumerações para Tipos Personalizados
- Correspondência Poderosa de Padrões