예제

예제 (Examples)

이름 짓는 규칙은 설명만으로는 감이 잘 안 와요. 그래서 지금까지 이야기한 규칙들이 실제 코드에서 어떻게 적용되는지, 하나의 완성된 예제로 모아서 보여드릴게요. 아래 코드만 봐도 Zig의 명명 규칙(naming convention)이 대략 어떻게 흘러가는지 파악할 수 있어요.

출처: Zig Documentation

본문

다음은 style_example.zig의 내용이에요. 여기 있는 패턴들을 하나씩 짚어보면 규칙이 머릿속에 정리가 돼요.

const namespace_name = @import("dir_name/file_name.zig");
const TypeName = @import("dir_name/TypeName.zig");
var global_var: i32 = undefined;
const const_name = 42;
const PrimitiveTypeAlias = f32;

const StructName = struct {
    field: i32,
};
const StructAlias = StructName;

fn functionName(param_name: TypeName) void {
    var functionPointer = functionName;
    functionPointer();
    functionPointer = otherFunction;
    functionPointer();
}
const functionAlias = functionName;

fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type {
    return List(ChildType, fixed_size);
}

fn ShortList(comptime T: type, comptime n: usize) type {
    return struct {
        field_name: [n]T,
        fn methodName() void {}
    };
}

// The word XML loses its casing when used in Zig identifiers.
const xml_document =
    \\<?xml version="1.0" encoding="UTF-8"?>
    \\<document>
    \\</document>
;
const XmlParser = struct {
    field: i32,
};

// The initials BE (Big Endian) are just another word in Zig identifier names.
fn readU32Be() u32 {}

재미있는 포인트가 몇 가지 보이네요.

  • 함수, 변수, 필드 이름은 소문자 스네이크 케이스(functionName이 아니라 function_name)로 써요. 반면 타입은 파스칼 케이스(TypeName, StructName)로 구분해요.
  • 함수 포인터나 타입 별칭은 그 대상의 이름 규칙을 그대로 따라가요. functionAlias, StructAlias처럼 원본과 같은 형태로 지어요.
  • ListTemplateFunction처럼 타입을 반환하는 함수도 결국 이름 규칙상 "함수"이기 때문에 파스칼 케이스를 쓰지 않아요. 다만 이 예제에서는 들여쓰기로 타입 생성의 성격을 드러내고 있네요.
  • 약어(줄임말)도 하나의 단어처럼 취급해요. XML이라는 단어가 식별자에 들어가면 대소문자 규칙이 그대로 적용돼서 xml_document처럼 소문자로 쓰이거나, XmlParser처럼 타입 위치에서 첫 글자만 대문자로 바뀌어요. Big Endian의 약어 BE도 마찬가지로 readU32Be에서 하나의 단어로 취급돼요.

더 많은 예제가 궁금하다면 Zig Standard Library를 살펴보세요.

더 알아보기

  • Style Guide — 예제가 속해 있는, Zig 명명 규칙 전반에 대한 안내
  • Zig Standard Library — 실제 코드가 이 규칙을 어떻게 지키는지 확인할 수 있는 표준 라이브러리 소개