0Pricing
Learn Rust Coding · 강의

데이터를 담은 열거형

변형에 값을 연결해 보세요.

데이터를 담은 열거형은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Variants Can Hold Data

So far our variants were just names. In Rust, a variant can also carry data inside parentheses.

This lets a single enum describe both the kind of value and the value itself.

enum Message {
    Quit,
    Move(i32, i32),
    Write(String),
}

A Variant with One Value

Put a type in parentheses to attach one piece of data to a variant.

Here Celsius(f64) means the Celsius variant holds a f64 number. You supply that number when you build the value.

enum Temperature {
    Celsius(f64),
    Fahrenheit(f64),
}

fn main() {
    let t = Temperature::Celsius(21.5);
    println!("Created a temperature");
}

Variants with Several Values

A variant can hold multiple values, separated by commas.

Move(i32, i32) stores two integers, perhaps an x and a y coordinate. You pass both when creating it.

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn main() {
    let r = Shape::Rectangle(3.0, 4.0);
    println!("Made a rectangle");
}

Extracting Data with match

To read the data inside a variant, name it in the pattern. The names become variables you can use in that arm.

Here Shape::Circle(r) binds the stored radius to r.

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn main() {
    let s = Shape::Circle(2.0);
    match s {
        Shape::Circle(r) => println!("radius {}", r),
        Shape::Rectangle(w, h) => println!("{} x {}", w, h),
    }
}

Using the Bound Values

Once data is bound to a name, you can compute with it like any variable.

This program matches a shape and calculates its area, returning the result from match.

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn main() {
    let s = Shape::Rectangle(3.0, 4.0);
    let area = match s {
        Shape::Circle(r) => 3.14 * r * r,
        Shape::Rectangle(w, h) => w * h,
    };
    println!("area = {}", area);
}

Different Data per Variant

Each variant can hold a different shape of data, and some can hold none at all.

This flexibility is what makes enums so expressive: one type models many distinct cases.

enum Message {
    Quit,
    Move(i32, i32),
    Write(String),
}

Struct-Like Variants

A variant can use named fields with curly braces, just like a struct. This makes the meaning of each field clear.

You build it by naming each field, and match it the same way.

enum Event {
    Click { x: i32, y: i32 },
    KeyPress(char),
}

fn main() {
    let e = Event::Click { x: 10, y: 20 };
    match e {
        Event::Click { x, y } => println!("click at {},{}", x, y),
        Event::KeyPress(c) => println!("key {}", c),
    }
}

Strings in Variants

Variants can hold owned data like a String. Matching gives you access to the text.

Note: matching by value moves the data out, which is fine here because we use it right away.

enum Message {
    Write(String),
    Quit,
}

fn main() {
    let m = Message::Write(String::from("hello"));
    match m {
        Message::Write(text) => println!("text: {}", text),
        Message::Quit => println!("bye"),
    }
}

The Standard Option Enum

Rust's built-in Option<T> is an enum with data: Some(T) holds a value and None holds nothing.

It is how Rust represents "maybe a value" without using null. You match it just like your own enums.

fn main() {
    let maybe: Option<i32> = Some(5);
    match maybe {
        Some(n) => println!("got {}", n),
        None => println!("nothing"),
    }
}

Putting It Together

This complete program models temperatures, then converts a Celsius reading to Fahrenheit inside a match.

Try changing the variant or its value and re-running.

enum Temperature {
    Celsius(f64),
    Fahrenheit(f64),
}

fn main() {
    let t = Temperature::Celsius(25.0);
    let f = match t {
        Temperature::Celsius(c) => c * 9.0 / 5.0 + 32.0,
        Temperature::Fahrenheit(f) => f,
    };
    println!("{} F", f);
}

When to Use Data Variants

Reach for data-carrying variants when each case naturally comes with extra information.

  • A Circle needs a radius.
  • A Write message needs its text.
  • A Move needs coordinates.

Bundling the data with the variant keeps related information together and type-safe.

Quick Check

Check your understanding of enums that carry data.

Recap

You learned that enum variants can carry data: a single value, several values, named struct-like fields, or none at all.

You read that data by naming it in a match pattern, like Circle(r). The standard Option type works the same way. Next you will refine matches with guards and bindings.

자주 묻는 질문

“데이터를 담은 열거형” 강의는 무료인가요?

네 — “데이터를 담은 열거형” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“데이터를 담은 열거형”에서 뭘 배우나요?

변형에 값을 연결해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“데이터를 담은 열거형” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 첫 열거형 정의하기
  2. 열거형 변형에 따라 매칭하기
  3. 데이터를 담은 열거형
  4. 매칭 가드와 바인딩
← Learn Rust Coding(으)로 돌아가기