사용자 정의 형식을 위한 열거형
여러 변형 중 하나가 될 수 있고 관련 데이터를 포함할 수도 있는 형식을 열거형으로 정의하는 방법을 익힙니다.
사용자 정의 형식을 위한 열거형은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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!
자주 묻는 질문
“사용자 정의 형식을 위한 열거형” 강의는 무료인가요?
네 — “사용자 정의 형식을 위한 열거형” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 3개의 강의가 포함되어 있습니다.
“사용자 정의 형식을 위한 열거형”에서 뭘 배우나요?
여러 변형 중 하나가 될 수 있고 관련 데이터를 포함할 수도 있는 형식을 열거형으로 정의하는 방법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“사용자 정의 형식을 위한 열거형” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 구조체 정의와 사용
- 사용자 정의 형식을 위한 열거형
- 강력한 패턴 매칭