100 Exercises To Learn Rust - 4.4 derives 풀기

// TODO: (deriavable) 트레이트 구현은 성공적으로 컴파일하기엔 빠진 부분이 있습니다.
// 고쳐보세요!
// # `Debug` primer
//
// `Debug`는 디버깅에 용이한 러스트 타입의 표현을 반환합니다.
// `assert_eq!`는 `Debug`를 구현하기를 요구하는데, 왜냐하면
// assertion이 실패할 경우, 비교하는 양쪽 모두를 터미널에 출력하려 할 것이기 때문입니다.
// 만약 비교된 타입이 `Debug`를 구현하지 않았다면, 어떻게 표현할지 알 수 없습니다!

#[derive(PartialEq)]
struct Ticket {
    title: String,
    description: String,
    status: String,
}

 

이전 절에서 Ticket 타입끼리 비교하기 위해 PartialEq 트레이트를 오버로딩했는데, 구조체의 구조가 변경된다면 오버로딩한 트레이트의 내용 역시 변경되어야 하므로 번거롭다.

 

derive 매크로는 기본적인 트레이트를 자동으로 구현한다.

 

위의 기본 코드를 그대로 테스트하면 다음과 같은 오류가 발생한다.

error[E0277]: `Ticket` doesn't implement `Debug`
  --> exercises\04_traits\04_derive\src\lib.rs:87:9
   |
87 |         assert_ne!(ticket1, ticket2);
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Ticket` cannot be formatted using `{:?}`
   |
   = help: the trait `Debug` is not implemented for `Ticket`
   = note: add `#[derive(Debug)]` to `Ticket` or manually `impl Debug for Ticket`
   = note: this error originates in the macro `assert_ne` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider annotating `Ticket` with `#[derive(Debug)]`
   |
11 + #[derive(Debug)]

 

주석에서 설명하고 있듯이 assert\_eq가 실패할 경우 정보를 출력해야 하는데, 이를 위해서는 Debug 매크로가 필요하기 때문이다.

 

따라서 다음과 같이 Debug 매크로를 구현하도록 타입에 추가한다.

#[derive(PartialEq, Debug)]
struct Ticket {
    title: String,
    description: String,
    status: String,
}