Rust 표준 라이브러리의 출력 가능한 타입

Beginner

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

소개

이 랩에서는 std::fmt 형식 지정 트레이트를 사용하기 위해, 타입이 출력 가능하도록 구현되어야 하며, 이는 std 라이브러리의 타입에 대해 자동으로 제공될 수 있다는 점을 설명합니다. 다른 타입의 경우, fmt::Debug 트레이트를 파생하여 출력을 활성화할 수 있습니다. fmt::Debug 트레이트는 출력 가능한 타입을 쉽게 구현할 수 있게 해주며, 반면 fmt::Display는 수동으로 구현해야 합니다. fmt::Debug 트레이트는 모든 타입이 출력을 위한 구현을 파생할 수 있도록 하며, std 라이브러리 타입의 {:?}에도 동일하게 적용됩니다. 또한, 이 랩에서는 {:?}를 사용하여 출력하는 방법을 언급하고, 다양한 타입을 출력하는 방법을 예시로 제공합니다. 추가적으로, 데이터 구조의 보다 우아한 표현을 제공하는 {:#?}를 사용한 "pretty printing"의 개념을 소개합니다. 마지막으로, fmt::Display를 수동으로 구현하여 타입의 표시를 제어할 수 있다는 점을 언급합니다.

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

Debug (디버그)

std::fmt 형식 지정 trait를 사용하려는 모든 타입은 출력을 위한 구현이 필요합니다. 자동 구현은 std 라이브러리와 같은 타입에 대해서만 제공됩니다. 다른 모든 타입은 반드시 어떤 방식으로든 수동으로 구현되어야 합니다.

fmt::Debug trait는 이를 매우 간단하게 만들어줍니다. 모든 타입은 fmt::Debug 구현을 derive (자동으로 생성) 할 수 있습니다. 이는 fmt::Display에는 해당되지 않으며, fmt::Display는 수동으로 구현해야 합니다.

// This structure cannot be printed either with `fmt::Display` or
// with `fmt::Debug`.
struct UnPrintable(i32);

// The `derive` attribute automatically creates the implementation
// required to make this `struct` printable with `fmt::Debug`.
#[derive(Debug)]
struct DebugPrintable(i32);

모든 std 라이브러리 타입은 {:?}로도 자동으로 출력 가능합니다.

// Derive the `fmt::Debug` implementation for `Structure`. `Structure`
// is a structure which contains a single `i32`.
#[derive(Debug)]
struct Structure(i32);

// Put a `Structure` inside of the structure `Deep`. Make it printable
// also.
#[derive(Debug)]
struct Deep(Structure);

fn main() {
    // Printing with `{:?}` is similar to with `{}`.
    println!("{:?} months in a year.", 12);
    println!("{1:?} {0:?} is the {actor:?} name.",
             "Slater",
             "Christian",
             actor="actor's");

    // `Structure` is printable!
    println!("Now {:?} will print!", Structure(3));

    // The problem with `derive` is there is no control over how
    // the results look. What if I want this to just show a `7`?
    println!("Now {:?} will print!", Deep(Structure(7)));
}

따라서 fmt::Debug는 확실히 출력을 가능하게 하지만, 약간의 우아함을 희생합니다. Rust 는 또한 {:#?}를 사용한 "pretty printing"을 제공합니다.

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

fn main() {
    let name = "Peter";
    let age = 27;
    let peter = Person { name, age };

    // Pretty print
    println!("{:#?}", peter);
}

fmt::Display를 수동으로 구현하여 표시를 제어할 수 있습니다.

요약

축하합니다! Debug 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 실력을 향상시킬 수 있습니다.