0Pricing
Learn Rust Coding · 강의

제네릭 구조체와 열거형

유연한 데이터 형식을 만들어 보세요.

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

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

Generic Data Structures

Just like functions, structs and enums can be generic over one or more types. This lets a single definition hold values of any type.

The standard library is built this way: Vec<T>, Option<T>, and Result<T, E> are all generic.

A Generic Struct

Declare the type parameter after the struct name, then use it for fields. Here Point stores two values of the same type T.

One definition now serves integer points, float points, and more.

struct Point<T> {
    x: T,
    y: T,
}

Constructing Generic Structs

When you create an instance, the compiler infers T from the field values. Both fields must agree on the same type.

This program builds an integer point and a float point from the same struct.

struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1.5, y: 4.0 };
    println!("{} {}", a.x, b.y);
}

Mixed Type Parameters

Using two parameters lets fields differ. Pair<T, U> can hold an integer and a string at the same time.

Choose one parameter when fields must match, and several when they may vary.

struct Pair<T, U> {
    first: T,
    second: U,
}

Methods on Generic Structs

To add methods, repeat the type parameter on the impl block: impl<T> Point<T>. The parameter after impl declares it; after the type name it applies it.

Here a getter returns a reference to the x field.

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

Methods With Bounds

You can write methods only for certain concrete types or for types meeting a bound. This impl applies just to Point<f64>.

So dist_from_origin exists on float points but not integer points.

struct Point<T> { x: T, y: T }

impl Point<f64> {
    fn dist_from_origin(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}

A Generic Enum

Enums are generic too. Each variant can carry generic data. This mirrors the standard Option, which is either Some(T) or None.

Defining your own helps you see how the library type works.

enum Maybe<T> {
    Just(T),
    Nothing,
}

Two Parameters in an Enum

Result uses two parameters so the success and error values can differ. Here is a simplified version.

Multiple type parameters in enums power flexible error handling across the ecosystem.

enum Either<L, R> {
    Left(L),
    Right(R),
}

Matching Generic Enums

You pattern match generic enums exactly like concrete ones. The bound payload becomes a binding inside the arm.

This program unwraps a custom Maybe and prints the contained value or a fallback.

enum Maybe<T> { Just(T), Nothing }

fn main() {
    let m: Maybe<i32> = Maybe::Just(5);
    match m {
        Maybe::Just(n) => println!("got {}", n),
        Maybe::Nothing => println!("empty"),
    }
}

Wrapping a Value

A common pattern is a wrapper struct with one field of type T plus helper methods. Here Wrapper stores and returns any value.

This is the foundation of newtype patterns and smart-pointer-like types.

struct Wrapper<T> { inner: T }

impl<T> Wrapper<T> {
    fn new(v: T) -> Self {
        Wrapper { inner: v }
    }
}

fn main() {
    let w = Wrapper::new("hi");
    println!("{}", w.inner);
}

No Runtime Overhead

Generic structs and enums are also monomorphized. Point<i32> and Point<f64> become two distinct, fully specialized types after compilation.

There is no hidden indirection or tag for the generic type itself.

Quick Check

Test your understanding of generic structs and enums.

Recap

Structs and enums declare type parameters after their name and use them in fields and variants, enabling reusable containers like Option and Result.

Methods repeat parameters on impl<T>, and you can write specialized impl blocks for concrete types. Everything is monomorphized for zero overhead.

자주 묻는 질문

“제네릭 구조체와 열거형” 강의는 무료인가요?

네 — “제네릭 구조체와 열거형” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 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개 중 2번째 강의입니다.

“제네릭 구조체와 열거형” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 제네릭 함수
  2. 제네릭 구조체와 열거형
  3. 트레이트 제약
  4. where 절과 여러 제약
← Learn Rust Coding(으)로 돌아가기