Rust 별칭: 코드 가독성 향상

Beginner

This tutorial is from open-source community. Access the source code

소개

이 실습에서는 Rust 에서의 별칭 (aliasing) 에 대해 배웁니다. 별칭은 type 문을 사용하여 기존 타입에 새로운 이름을 부여하는 기능입니다. 별칭은 특정 명명 규칙을 따라야 하며, 기본 타입이나 사용자 정의 타입에 대한 새로운 이름을 만들 수 있습니다. 별칭의 주요 목적은 코드 중복을 줄이고 가독성을 높이는 것입니다.

참고: 실습에서 파일 이름을 지정하지 않으면 원하는 파일 이름을 사용할 수 있습니다. 예를 들어 main.rs를 사용하고 rustc main.rs && ./main으로 컴파일 및 실행할 수 있습니다.

Aliasing

The type statement can be used to give a new name to an existing type. Types must have UpperCamelCase names, or the compiler will raise a warning. The exception to this rule are the primitive types: usize, f32, etc.

// `NanoSecond`, `Inch`, and `U64` are new names for `u64`.
type NanoSecond = u64;
type Inch = u64;
type U64 = u64;

fn main() {
    // `NanoSecond` = `Inch` = `U64` = `u64`.
    let nanoseconds: NanoSecond = 5 as U64;
    let inches: Inch = 2 as U64;

    // Note that type aliases *don't* provide any extra type safety, because
    // aliases are *not* new types
    println!("{} nanoseconds + {} inches = {} unit?",
             nanoseconds,
             inches,
             nanoseconds + inches);
}

The main use of aliases is to reduce boilerplate; for example the io::Result<T> type is an alias for the Result<T, io::Error> type.

별칭

type 문을 사용하여 기존 타입에 새로운 이름을 줄 수 있습니다. 타입은 UpperCamelCase 이름을 가져야 하며, 그렇지 않으면 컴파일러가 경고를 발생시킵니다. 이 규칙의 예외는 기본 타입 (usize, f32 등) 입니다.

// `NanoSecond`, `Inch`, `U64` 는 `u64` 의 새로운 이름입니다.
type NanoSecond = u64;
type Inch = u64;
type U64 = u64;

fn main() {
    // `NanoSecond` = `Inch` = `U64` = `u64`.
    let nanoseconds: NanoSecond = 5 as U64;
    let inches: Inch = 2 as U64;

    // 별칭은 *새로운 타입*이 아니므로 추가적인 타입 안전성을 제공하지 않습니다.
    println!("{} 나노초 + {} 인치 = {} 단위?",
             nanoseconds,
             inches,
             nanoseconds + inches);
}

별칭의 주요 용도는 반복적인 코드를 줄이는 것입니다. 예를 들어, io::Result<T> 타입은 Result<T, io::Error> 타입의 별칭입니다.