0Pricing
Zig Academy · 강의

제네릭 자료 구조

타입을 반환하는 함수 패턴을 알아봅니다.

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

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

Generic Containers in Zig

To make a data structure work for any element type, you write a function that takes a type and returns a brand-new struct type. 📦

A Function That Returns a Type

The trick is that a function can have a return type of type. It computes and hands back a fresh type at compile time.

fn List(comptime T: type) type {
    return struct {};
}

Build the Struct Inside

Inside the function, define a struct whose fields use the type parameter T. Each call produces a struct tailored to that element type.

fn Box(comptime T: type) type {
    return struct { value: T };
}

Name the Resulting Type

Call the type-returning function and store the result in a const. Now you have a concrete type ready to use.

const IntBox = Box(i32);

Create an Instance

Use that named type just like any struct. Here we make a Box that holds the integer forty-two.

const b = IntBox{ .value = 42 };

Add Methods to the Inner Struct

The returned struct can contain methods too. They see the type parameter, so they stay fully generic.

fn Box(comptime T: type) type {
    return struct {
        value: T,
        fn get(self: @This()) T {
            return self.value;
        }
    };
}

Reach the Type with @This

Inside an anonymous returned struct you cannot name it directly, so methods use @This() to refer to the enclosing struct type.

self: @This()

Many Types from One Definition

Call the function with different types and you get distinct structs. Box(i32) and Box(f64) are separate, fully checked types.

const FloatBox = Box(f64);

This Powers the Standard Library

Zig's own ArrayList and HashMap are built this exact way: functions that take a type and return a configured container type.

const Ints = std.ArrayList(i32);

Resolved Entirely at Compile Time

All of this type construction happens during the build, so a generic container has the same cost as a hand-written one.

Carry an Allocator When Growing

Containers that grow store an allocator field, passed in at init, so the generic type stays explicit about where its memory comes from.

return struct {
    items: []T,
    alloc: std.mem.Allocator,
};

Quick Check

You want a generic stack that works for any element type in Zig. What pattern do you use?

Recap

Write a function that takes a type and returns a struct type. Each call yields a concrete, specialized container. This is how std builds its collections. 🎯

자주 묻는 질문

“제네릭 자료 구조” 강의는 무료인가요?

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

“제네릭 자료 구조”에서 뭘 배우나요?

타입을 반환하는 함수 패턴을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 Zig Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Zig Academy을(를) 시작하는 데 경험이 필요한가요?

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

“제네릭 자료 구조” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. 타입을 받는 함수
  2. 제네릭 자료 구조
  3. @TypeOf와 타입 리플렉션
  4. anytype 매개변수
← Zig Academy(으)로 돌아가기