$ cargo run --stage 7

7단계: 트레이트와 제네릭 강의 노트

제네릭 함수와 구조체, 트레이트 정의·기본 구현·고아 규칙, 트레이트 경계와 where, impl Trait 와 dyn Trait, 단형화와 vtable, derive 할 수 있는 표준 트레이트, Display 구현과 연산자 오버로딩을 실제 컴파일 결과와 함께 정리합니다.

기간 25~28주구성 5개 단원
1단원

제네릭: 타입을 빈칸으로 남겨 두기

학습 목표
  • 타입만 다르고 하는 일이 같은 함수를 제네릭 함수 하나로 합칠 수 있다.
  • 타입 매개변수에 트레이트 경계가 왜 필요한지 컴파일러 오류로 설명할 수 있다.
  • 제네릭 구조체와 impl<T>, 특정 타입에만 붙는 impl 블록을 구분할 수 있다.
  • 단형화(monomorphization)가 무엇이고 실행 속도와 실행 파일 크기에 어떤 영향을 주는지 말할 수 있다.

1.1같은 일을 하는 함수가 둘

점수 목록에서 가장 큰 값을 찾는 함수와 키 목록에서 가장 큰 값을 찾는 함수를 따로 만들었다고 해 봅시다. 두 함수의 몸통은 한 글자도 다르지 않고, 다른 것은 매개변수와 반환값의 타입(i32와 f64)뿐입니다.

src/bin/dup.rs
fn top_score(scores: &[i32]) -> i32 {
    let mut top = scores[0];
    for &s in scores {
        if s > top {
            top = s;
        }
    }
    top
}

fn top_height(heights: &[f64]) -> f64 {
    let mut top = heights[0];
    for &h in heights {
        if h > top {
            top = h;
        }
    }
    top
}

fn main() {
    println!("최고 점수: {}", top_score(&[72, 95, 88]));
    println!("최고 키: {}", top_height(&[162.5, 171.0, 158.3]));
}
$ cargo run --bin dup
   Compiling generic v0.1.0 (…/p7/generic)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/dup`
최고 점수: 95
최고 키: 171

문자 목록, 문자열 목록이 생길 때마다 함수를 또 복사해야 한다면 고칠 곳도 그만큼 늘어납니다. (f64 값 171.0은 {}로 찍으면 171로 보입니다. 표시 방식일 뿐입니다.)

1.2제네릭 함수와 타입 매개변수

제네릭(generic)은 타입 자리를 비워 두고 이름을 붙여 쓰는 방법입니다. 함수 이름 뒤 꺾쇠 안에 T처럼 타입 매개변수(type parameter)를 선언하면, 함수 몸통에서 T를 진짜 타입처럼 쓸 수 있습니다. 호출하는 쪽이 넘긴 값의 타입을 보고 컴파일러가 T를 정합니다.

src/bin/largest.rs
fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut top = &list[0];
    for item in list {
        if item > top {
            top = item;
        }
    }
    top
}

fn main() {
    let scores = [72, 95, 88];
    let heights = [162.5, 171.0, 158.3];
    let initials = ['김', '이', '박'];
    let names = ["민지", "서준", "하린"];

    println!("최고 점수: {}", largest(&scores));
    println!("최고 키: {}", largest(&heights));
    println!("가장 뒤 글자: {}", largest(&initials));
    println!("사전 순 마지막 이름: {}", largest(&names));
}
$ cargo run --bin largest
   Compiling generic v0.1.0 (…/p7/generic)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/largest`
최고 점수: 95
최고 키: 171
가장 뒤 글자: 이
사전 순 마지막 이름: 하린

첫 줄 fn largest<T: PartialOrd>(list: &[T]) -> &T를 왼쪽부터 읽으면 이렇습니다.

  • <T: PartialOrd>: 타입 매개변수 T를 선언하고, 그 T는 PartialOrd 트레이트를 구현한 타입이어야 한다는 트레이트 경계(trait bound)를 붙였습니다. PartialOrd는 <, > 같은 크기 비교를 할 수 있다는 표준 트레이트입니다.
  • list: &[T]: T 값들이 든 슬라이스를 빌려 받습니다(슬라이스는 3단계).
  • -> &T: 목록 안의 한 칸을 가리키는 참조를 돌려줍니다. 값을 돌려주려면 T가 복사 가능해야 하니 참조가 더 많은 타입에 통합니다.

한 함수로 네 타입을 모두 처리했습니다. 문자와 문자열은 유니코드 코드값 순서로 비교합니다. 한글 완성형 글자는 코드값이 가나다순으로 놓여 있어서 '이'가 '김', '박'보다 크고, "하린"이 가장 뒤에 옵니다.

1.3경계가 없으면 아무것도 못 한다

경계 : PartialOrd를 지우면 어떻게 될까요? 컴파일러는 T에 대해 "어떤 타입이든 될 수 있다"는 것밖에 모릅니다. 비교할 수 없는 타입도 들어올 수 있으니 >를 허락하지 않습니다.

src/bin/no_bound.rs
fn largest<T>(list: &[T]) -> &T {
    let mut top = &list[0];
    for item in list {
        if item > top {
            top = item;
        }
    }
    top
}

fn main() {
    println!("{}", largest(&[3, 7, 5]));
}
$ cargo build --bin no_bound
   Compiling errs v0.1.0 (…/p7/errs)
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> src/bin/no_bound.rs:4:17
  |
4 |         if item > top {
  |            ---- ^ --- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
  |             ++++++++++++++++++++++

For more information about this error, try `rustc --explain E0369`.
error: could not compile `errs` (bin "no_bound") due to 1 previous error

메시지를 읽는 순서는 지금까지와 같습니다. error[E0369]는 "이항 연산을 이 타입에 쓸 수 없다"는 오류 번호이고, --> src/bin/no_bound.rs:4:17은 4번째 줄 17번째 글자, 곧 > 기호를 가리킵니다. 양쪽 밑줄에 붙은 &T는 두 피연산자의 타입입니다. 가장 쓸모 있는 것은 help 줄로, 1번째 줄에 std::cmp::PartialOrd 경계를 더하라고 +++ 표시로 고칠 곳까지 알려 줍니다.

이것이 Rust 제네릭의 핵심 규칙입니다. 제네릭 함수의 몸통은 경계로 약속된 일만 할 수 있습니다. 그 대신 몸통이 한 번 컴파일되면, 경계를 만족하는 어떤 타입으로 불러도 몸통에서는 오류가 나지 않습니다.

왜 이렇게 만들었을까

언어에 따라서는 실제 타입을 끼워 넣어 본 뒤에야 제네릭 몸통의 오류를 찾기도 하는데, 그러면 오류가 호출한 곳이 아니라 라이브러리 안쪽에서 보고되기 쉽습니다. Rust는 경계를 함수 머리에 적게 해서, 함수를 만든 사람과 쓰는 사람의 약속을 서명(signature)만 보고 검사합니다. 서명이 곧 문서가 되는 셈입니다.

1.4제네릭 구조체와 impl

구조체의 필드 타입도 비워 둘 수 있습니다. 구조체 이름 뒤에 <T>를 쓰고 필드에 T를 씁니다. 메서드를 붙일 때는 impl<T> Pair<T>처럼 impl 뒤에도 <T>를 써서 "지금부터 쓰는 T는 타입 매개변수다"라고 먼저 밝힙니다.

src/bin/pair.rs
#[derive(Debug)]
struct Pair<T> {
    first: T,
    second: T,
}

impl<T> Pair<T> {
    fn new(first: T, second: T) -> Self {
        Pair { first, second }
    }

    fn swap(self) -> Pair<T> {
        Pair { first: self.second, second: self.first }
    }
}

impl Pair<f64> {
    fn average(&self) -> f64 {
        (self.first + self.second) / 2.0
    }
}

fn main() {
    let names = Pair::new("민지", "서준");
    let scores = Pair::new(80, 95);
    let temps = Pair::new(18.5, 26.0);

    println!("{:?}", names.swap());
    println!("{:?}", scores);
    println!("평균 기온: {}", temps.average());
}
$ cargo run --bin pair
   Compiling generic v0.1.0 (…/p7/generic)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/pair`
Pair { first: "서준", second: "민지" }
Pair { first: 80, second: 95 }
평균 기온: 22.25

impl Pair<f64>에는 impl 뒤에 <T>가 없습니다. 이 블록은 T가 정확히 f64일 때만 해당하는 구체적인 구현이라서 average는 Pair<f64>에만 생깁니다. 나눗셈과 덧셈이 되는 타입이 f64라는 것을 컴파일러가 알기 때문에 몸통에서 +와 /를 마음대로 씁니다. 정수 쌍에 average를 부르면 메서드가 없다는 오류가 납니다.

src/bin/no_avg.rs
fn main() {
    let p = Pair { first: 80, second: 95 };
    println!("{}", p.average());
}
$ cargo build --bin no_avg
   Compiling errs v0.1.0 (…/p7/errs)
error[E0599]: no method named `average` found for struct `Pair<{integer}>` in the current scope
  --> src/bin/no_avg.rs:14:22
   |
 1 | struct Pair<T> {
   | -------------- method `average` not found for this struct
...
14 |     println!("{}", p.average());
   |                      ^^^^^^^ method not found in `Pair<{integer}>`
   |
   = note: the method was found for `Pair<f64>`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `errs` (bin "no_avg") due to 1 previous error

{integer}는 "아직 정하지 않은 정수 타입"이라는 뜻이고, note가 그 메서드는 Pair<f64>에 있다고 알려 줍니다.

Pair<T>는 두 필드가 같은 타입 T입니다. 정수와 실수를 섞으면, 첫 필드에서 T가 정수로 정해진 뒤 둘째 필드가 맞지 않아 E0308이 납니다.

src/bin/mixed.rs
struct Pair<T> {
    first: T,
    second: T,
}

fn main() {
    let p = Pair { first: 5, second: 2.5 };
    println!("{} {}", p.first, p.second);
}
$ cargo build --bin mixed
   Compiling errs v0.1.0 (…/p7/errs)
error[E0308]: mismatched types
 --> src/bin/mixed.rs:7:38
  |
7 |     let p = Pair { first: 5, second: 2.5 };
  |                                      ^^^ expected integer, found floating-point number

For more information about this error, try `rustc --explain E0308`.
error: could not compile `errs` (bin "mixed") due to 1 previous error

서로 다른 타입을 담으려면 타입 매개변수를 둘 둡니다. 쉼표로 늘어놓으면 됩니다.

src/bin/entry.rs
#[derive(Debug)]
struct Entry<K, V> {
    key: K,
    value: V,
}

impl<K, V> Entry<K, V> {
    fn key(&self) -> &K {
        &self.key
    }
}

fn main() {
    let book = Entry { key: "ISBN-0001", value: 3 };
    let seat = Entry { key: 12, value: "창가" };
    let grade = Entry { key: '수', value: 92.5 };

    println!("{:?}", book);
    println!("{:?}", seat);
    println!("열쇠 {} → 값 {}", grade.key(), grade.value);
}
$ cargo run --bin entry
   Compiling generic v0.1.0 (…/p7/generic)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/entry`
Entry { key: "ISBN-0001", value: 3 }
Entry { key: 12, value: "창가" }
열쇠 수 → 값 92.5

앞 단계의 Option, Result, Vec, HashMap도 모두 표준 라이브러리의 제네릭 타입입니다. Option은 대략 이런 모양입니다.

enum Option<T> {
    None,
    Some(T),
}

1.5단형화: 제네릭은 실행 속도를 깎지 않는다

컴파일러는 프로그램에서 실제로 쓰인 타입마다 T를 그 타입으로 바꾼 함수를 따로 만들어 넣습니다. 이 과정을 단형화(monomorphization)라고 합니다. 아래는 std::any::type_name으로 호출마다 T가 무엇이 되었는지 찍어 봅니다.

src/bin/mono.rs
use std::any::type_name;

fn describe<T>(_value: T) {
    println!("이 복사본은 T = {} 로 만들어졌습니다", type_name::<T>());
}

fn main() {
    describe(42);
    describe(3.5);
    describe("안녕");
    describe('가');
    describe(42);
}
$ cargo run --bin mono
   Compiling generic v0.1.0 (…/p7/generic)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/mono`
이 복사본은 T = i32 로 만들어졌습니다
이 복사본은 T = f64 로 만들어졌습니다
이 복사본은 T = &str 로 만들어졌습니다
이 복사본은 T = char 로 만들어졌습니다
이 복사본은 T = i32 로 만들어졌습니다

호출이 다섯 번이지만 타입은 i32, f64, &str, char 네 가지이므로, 컴파일러가 만드는 describe의 복사본도 네 개입니다. 마지막 describe(42)는 이미 있는 i32용 복사본을 다시 부릅니다. (type_name의 글자 모양은 버전에 따라 달라질 수 있는 진단용입니다.)

fn describe<T> 하나
→
컴파일러쓰인 타입을 모은다
→
describe::<i32>
describe::<f64>
describe::<&str>
describe::<char>

결과로 생긴 함수들은 그 타입으로 손수 쓴 함수와 다를 바 없으므로 제네릭을 써도 실행이 느려지지 않습니다. 대신 쓰인 타입이 많을수록 컴파일 시간과 실행 파일 크기가 늘 수 있습니다. 실행할 때 고르는 방식은 4단원에서 봅니다.

C와 비교

C에는 제네릭이 없어서, 여러 타입을 다루는 표준 함수 qsort는 원소를 void *로 받고 비교 함수를 함수 포인터로 받습니다. 타입 정보가 지워지므로 잘못된 비교 함수를 넘겨도 컴파일러가 막지 못합니다. 아래는 실수 배열에 정수 비교 함수를 넘긴 예입니다. -Wall을 켜도 경고가 없고, 결과는 정렬되지 않았습니다.

c/sort.c
#include <stdio.h>
#include <stdlib.h>

/* qsort 는 void* 로 받으므로 무슨 타입인지 모른다 */
static int cmp_int(const void *a, const void *b) {
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

int main(void) {
    int scores[] = {72, 95, 88};
    double heights[] = {171.5, 158.25, 162.0};

    qsort(scores, 3, sizeof(int), cmp_int);
    printf("%d %d %d\n", scores[0], scores[1], scores[2]);

    /* 실수 배열에 정수 비교 함수를 넘겨도 컴파일된다 */
    qsort(heights, 3, sizeof(double), cmp_int);
    printf("%.2f %.2f %.2f\n", heights[0], heights[1], heights[2]);
    return 0;
}
$ gcc -Wall -o sort sort.c && ./sort
72 88 95
171.50 158.25 162.00

이 컴퓨터에서는 비교 함수가 실수 8바이트 가운데 앞 4바이트만 정수로 읽는데, 이 세 값은 그 4바이트가 모두 0이라 "모두 같다"고 판단했습니다. Rust의 largest는 T마다 따로 단형화되고 PartialOrd 경계로 비교 방법이 타입에 묶여 있어서, 이런 엇갈림이 컴파일 단계에서 막힙니다.

핵심 정리
  • fn 이름<T: 경계>(…)로 타입을 비워 둔 함수를 만들고, 호출할 때 컴파일러가 T를 정한다.
  • 제네릭 함수의 몸통은 경계로 약속한 기능만 쓸 수 있다. 경계가 빠지면 E0369, E0277 같은 오류가 나고 help가 고칠 곳을 알려 준다.
  • struct Pair<T>와 impl<T> Pair<T>는 모든 T에, impl Pair<f64>는 그 타입에만 메서드를 붙인다.
  • 단형화로 쓰인 타입마다 복사본이 생기므로 실행 비용은 없고, 컴파일 시간과 파일 크기가 늘 수 있다.
참고 공식 책 10.1 Generic Data Types · std 문서 std::cmp::PartialOrd, std::any::type_name · rustc 오류 색인 E0369, E0599
2단원

트레이트: 공통 동작에 이름 붙이기

학습 목표
  • trait로 메서드 서명의 묶음을 정의하고 impl 트레이트 for 타입으로 구현할 수 있다.
  • 기본 구현을 만들고, 필요한 타입에서만 덮어쓸 수 있다.
  • E0046(구현 빠짐) 메시지를 읽고 고칠 수 있다.
  • 고아 규칙이 무엇을 막는지 한 문장으로 말할 수 있다.

2.1트레이트 정의와 구현

트레이트(trait)는 "이런 메서드들을 가지고 있다"는 약속에 이름을 붙인 것입니다. 정의할 때는 메서드의 서명만 쓰고 몸통 대신 세미콜론을 찍습니다. 그리고 각 타입이 impl 트레이트이름 for 타입이름 { … } 블록에서 그 메서드들을 실제로 만듭니다.

이 단계의 예제는 하루 교통비 계산기입니다. 버스, 지하철, 택시는 서로 다른 구조체지만 모두 "이름을 말할 수 있고 요금을 계산할 수 있다"는 공통점이 있습니다. 그 공통점을 Fare 트레이트로 묶습니다. (요금 규칙은 설명을 위해 지어낸 것입니다.)

src/bin/basic.rs
trait Fare {
    fn name(&self) -> String;
    fn fare(&self) -> u32;
}

struct Bus {
    km: u32,
}

struct Subway {
    stations: u32,
}

impl Fare for Bus {
    fn name(&self) -> String {
        format!("버스 {}km", self.km)
    }

    fn fare(&self) -> u32 {
        if self.km <= 10 { 1500 } else { 1500 + (self.km - 10) * 100 }
    }
}

impl Fare for Subway {
    fn name(&self) -> String {
        format!("지하철 {}개 역", self.stations)
    }

    fn fare(&self) -> u32 {
        1400 + self.stations / 5 * 100
    }
}

fn main() {
    let bus = Bus { km: 14 };
    let subway = Subway { stations: 12 };

    println!("{}: {}원", bus.name(), bus.fare());
    println!("{}: {}원", subway.name(), subway.fare());
}
$ cargo run --bin basic
   Compiling fare v0.1.0 (…/p7/fare)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/basic`
버스 14km: 1900원
지하철 12개 역: 1600원

트레이트 메서드를 부르는 모양은 4단계에서 배운 일반 메서드와 똑같이 bus.fare()입니다. 다른 점은, Bus와 Subway가 같은 이름의 메서드를 "우연히" 가진 것이 아니라 Fare라는 같은 약속을 지킨다는 사실을 컴파일러가 안다는 것입니다. 이 사실 덕분에 3단원에서 "Fare를 구현한 무엇이든 받는 함수"를 쓸 수 있습니다.

2.2약속을 다 지키지 않으면

트레이트의 메서드 가운데 몸통이 없는 것은 구현하는 쪽이 모두 써야 합니다. 하나라도 빠지면 E0046이 납니다.

src/bin/missing.rs
trait Fare {
    fn name(&self) -> String;
    fn fare(&self) -> u32;
}

struct Bike {
    minutes: u32,
}

impl Fare for Bike {
    fn name(&self) -> String {
        format!("공유 자전거 {}분", self.minutes)
    }
}

fn main() {
    let b = Bike { minutes: 30 };
    println!("{}", b.name());
}
$ cargo build --bin missing
   Compiling errs v0.1.0 (…/p7/errs)
error[E0046]: not all trait items implemented, missing: `fare`
  --> src/bin/missing.rs:10:1
   |
 3 |     fn fare(&self) -> u32;
   |     ---------------------- `fare` from trait
...
10 | impl Fare for Bike {
   | ^^^^^^^^^^^^^^^^^^ missing `fare` in implementation

For more information about this error, try `rustc --explain E0046`.
error: could not compile `errs` (bin "missing") due to 1 previous error

오류는 10번째 줄 impl Fare for Bike를 가리키고, 빠진 fare가 트레이트의 3번째 줄에 있다고 보여 줍니다.

2.3기본 구현

트레이트 안의 메서드에 몸통을 써 두면 그것이 기본 구현(default implementation)이 됩니다. 구현하는 타입은 그 메서드를 쓰지 않아도 되고, 원하면 같은 이름으로 다시 써서 덮어씁니다. 기본 구현은 같은 트레이트의 다른 메서드를 불러도 됩니다. 아래 receipt는 아직 몸통이 정해지지 않은 name과 fare를 불러서 영수증 한 줄을 만듭니다.

src/bin/default.rs
trait Fare {
    fn name(&self) -> String;
    fn fare(&self) -> u32;

    // 기본 구현: 위의 두 메서드를 써서 영수증 한 줄을 만든다
    fn receipt(&self) -> String {
        format!("{} ..... {}원", self.name(), self.fare())
    }
}

struct Bus {
    km: u32,
}

struct Taxi {
    km: u32,
    night: bool,
}

impl Fare for Bus {
    fn name(&self) -> String {
        format!("버스 {}km", self.km)
    }

    fn fare(&self) -> u32 {
        if self.km <= 10 { 1500 } else { 1500 + (self.km - 10) * 100 }
    }
    // receipt 는 쓰지 않았으니 기본 구현을 그대로 쓴다
}

impl Fare for Taxi {
    fn name(&self) -> String {
        format!("택시 {}km", self.km)
    }

    fn fare(&self) -> u32 {
        let base = 4800 + self.km * 1000;
        if self.night { base * 6 / 5 } else { base }
    }

    // 택시는 영수증 모양을 바꾼다 (기본 구현 덮어쓰기)
    fn receipt(&self) -> String {
        let when = if self.night { "심야" } else { "주간" };
        format!("[{}] {} ..... {}원", when, self.name(), self.fare())
    }
}

fn main() {
    let bus = Bus { km: 8 };
    let taxi = Taxi { km: 5, night: true };

    println!("{}", bus.receipt());
    println!("{}", taxi.receipt());
}
$ cargo run --bin default
   Compiling fare v0.1.0 (…/p7/fare)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/default`
버스 8km ..... 1500원
[심야] 택시 5km ..... 11760원

Bus는 receipt를 쓰지 않았으므로 기본 구현이 쓰였고, 그 안의 self.name()과 self.fare()는 Bus의 것이 불렸습니다. Taxi는 자기 receipt를 썼으므로 그쪽이 불렸습니다(4800 + 5000 = 9800원에 심야 20%를 더해 11760원). 9단계의 Iterator도 next 하나만 구현하면 많은 메서드가 기본 구현으로 따라옵니다.

흔한 실수

덮어쓴 메서드 안에서 기본 구현을 다시 부르는 문법은 없습니다. 공통 부분은 별도 메서드로 빼 두고 양쪽에서 부르세요.

2.4남의 타입에 구현하기와 고아 규칙

내가 만든 트레이트는 표준 라이브러리의 타입에도 구현할 수 있습니다. 아래는 Vec<u32>에 합계를 구하는 Total 트레이트를 붙인 예입니다. 이제 모든 Vec<u32> 값에 .total()을 부를 수 있습니다.

src/bin/foreign.rs
// 내가 만든 트레이트는 표준 라이브러리 타입에도 구현할 수 있다
trait Total {
    fn total(&self) -> u32;
}

impl Total for Vec<u32> {
    fn total(&self) -> u32 {
        let mut sum = 0;
        for x in self {
            sum += x;
        }
        sum
    }
}

fn main() {
    let spent = vec![1500, 1400, 9600];
    println!("오늘 교통비 합계: {}원", spent.total());
}
$ cargo run --bin foreign
   Compiling fare v0.1.0 (…/p7/fare)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/foreign`
오늘 교통비 합계: 12500원

그러나 남이 만든 트레이트를 남이 만든 타입에 구현하는 것은 금지입니다. 표준 라이브러리의 Display를 표준 라이브러리의 Vec<u32>에 구현하려 하면 E0117이 납니다.

src/bin/orphan.rs
use std::fmt;

impl fmt::Display for Vec<u32> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}개", self.len())
    }
}

fn main() {
    let spent = vec![1500, 1400];
    println!("{}", spent);
}
$ cargo build --bin orphan
   Compiling errs v0.1.0 (…/p7/errs)
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> src/bin/orphan.rs:3:1
  |
3 | impl fmt::Display for Vec<u32> {
  | ^^^^^^^^^^^^^^^^^^^^^^--------
  |                       |
  |                       `Vec` is not defined in the current crate
  |
  = note: impl doesn't have any local type before any uncovered type parameters
  = note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
  = note: define and implement a trait or new type instead

For more information about this error, try `rustc --explain E0117`.
error: could not compile `errs` (bin "orphan") due to 1 previous error

이것을 고아 규칙(orphan rule)이라고 합니다. 한 줄로 말하면 "트레이트와 타입 가운데 적어도 하나는 지금 크레이트에서 정의한 것이어야 한다"입니다. (제네릭이 섞이면 조금 더 복잡하며, 정확한 규칙은 Reference에 있습니다.) 이 규칙이 없다면 두 라이브러리가 각자 Vec<u32>에 Display를 구현했을 때 어느 쪽을 써야 할지 정할 수 없게 됩니다. 꼭 필요하면 메시지의 마지막 note가 권하듯 struct Spent(Vec<u32>);처럼 내 타입으로 한 번 감싸고(이런 감싸기를 뉴타입(newtype) 패턴이라고 부릅니다) 그 타입에 구현합니다.

핵심 정리
  • trait 이름 { fn 메서드(&self) -> 타입; }로 정의하고 impl 이름 for 타입 { … }으로 구현한다.
  • 몸통 없는 메서드는 모두 구현해야 한다(빠지면 E0046). 몸통 있는 메서드는 기본 구현이며 덮어쓸 수 있다.
  • 기본 구현은 같은 트레이트의 다른 메서드를 부를 수 있다.
  • 고아 규칙: 트레이트나 타입 중 하나는 내 크레이트의 것이어야 구현할 수 있다(어기면 E0117).
참고 공식 책 10.2 Traits: Defining Shared Behavior · Rust Reference "Implementations"의 Orphan rules · rustc 오류 색인 E0046, E0117
3단원

트레이트 경계: 받을 수 있는 타입 정하기

학습 목표
  • &impl Trait 인자와 <T: Trait> 경계를 서로 바꿔 쓸 수 있고 차이를 설명할 수 있다.
  • 여러 경계를 +로 잇고, 길어지면 where 절로 옮길 수 있다.
  • 경계를 만족할 때만 생기는 메서드를 만들 수 있다.
  • impl Trait 반환 타입의 쓰임과 한계(한 가지 타입만)를 설명할 수 있다.

3.1impl Trait 인자와 트레이트 경계

트레이트의 진짜 쓸모는 함수의 매개변수 타입 자리에 나타납니다. "버스를 받는 함수", "지하철을 받는 함수"를 따로 만들지 않고 "Fare를 구현한 무엇이든 받는 함수"를 한 번에 만듭니다. 쓰는 방법은 두 가지입니다.

src/bin/impl_arg.rs
// 1) impl Trait 인자: "Fare 를 구현한 무엇이든"
fn print_line(item: &impl Fare) {
    println!("{} → {}원", item.name(), item.fare());
}

// 2) 같은 뜻을 트레이트 경계로 쓴 것
fn with_points<T: Fare>(item: &T) -> u32 {
    item.fare() / 100
}

fn main() {
    let bus = Bus { km: 14 };
    let subway = Subway { stations: 7 };

    print_line(&bus);
    print_line(&subway);
    println!("적립 포인트: {}점", with_points(&bus) + with_points(&subway));
}
$ cargo run --bin impl_arg
   Compiling bounds v0.1.0 (…/p7/bounds)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/impl_arg`
버스 14km → 1900원
지하철 7개 역 → 1500원
적립 포인트: 34점

(위에 보이지 않는 1~31번째 줄은 2단원의 Fare, Bus, Subway 정의와 같습니다.) item: &impl Fare는 "Fare를 구현한 어떤 타입의 참조"라는 뜻이고, fn with_points<T: Fare>(item: &T)는 같은 뜻을 1단원의 트레이트 경계 문법으로 쓴 것입니다. impl Trait 인자는 이름 없는 타입 매개변수를 만드는 줄임 표현이어서, 두 함수 모두 Bus용과 Subway용으로 단형화됩니다. 지하철 7개 역은 1500원, 포인트는 19 + 15 = 34점입니다.

두 표기의 차이가 드러나는 곳은 매개변수가 여럿일 때입니다. fn f(a: &impl Fare, b: &impl Fare)는 a와 b가 서로 다른 타입이어도 되지만, fn f<T: Fare>(a: &T, b: &T)는 둘이 같은 타입 T여야 합니다(4단원에서 오류로 확인합니다).

경계를 만족하지 않는 타입을 넘기면, 이번에는 오류가 함수 몸통이 아니라 호출한 줄에서 납니다.

src/bin/not_fare.rs
trait Fare {
    fn fare(&self) -> u32;
}

struct Walk {
    minutes: u32,
}

fn print_fare(item: &impl Fare) {
    println!("{}원", item.fare());
}

fn main() {
    let w = Walk { minutes: 20 };
    print_fare(&w);
    println!("{}분", w.minutes);
}
$ cargo build --bin not_fare
   Compiling errs v0.1.0 (…/p7/errs)
error[E0277]: the trait bound `Walk: Fare` is not satisfied
  --> src/bin/not_fare.rs:15:16
   |
15 |     print_fare(&w);
   |     ---------- ^^ unsatisfied trait bound
   |     |
   |     required by a bound introduced by this call
   |
help: the trait `Fare` is not implemented for `Walk`
  --> src/bin/not_fare.rs:5:1
   |
 5 | struct Walk {
   | ^^^^^^^^^^^
help: this trait has no implementations, consider adding one
  --> src/bin/not_fare.rs:1:1
   |
 1 | trait Fare {
   | ^^^^^^^^^^
note: required by a bound in `print_fare`
  --> src/bin/not_fare.rs:9:27
   |
 9 | fn print_fare(item: &impl Fare) {
   |                           ^^^^ required by this bound in `print_fare`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `errs` (bin "not_fare") due to 1 previous error

E0277은 "필요한 트레이트를 구현하지 않았다"는 뜻으로 앞으로 가장 자주 만날 오류입니다. 15번째 줄의 &w에 밑줄이 있고, 마지막 note가 그 요구가 9번째 줄의 impl Fare 경계에서 왔다고 짚어 줍니다.

3.2여러 경계와 where 절

한 타입 매개변수에 경계를 여러 개 붙이려면 +로 잇습니다. 경계가 길어져서 함수 머리를 읽기 어려워지면, 반환 타입 뒤에 where 절(where clause)을 두고 거기로 옮깁니다. 뜻은 완전히 같습니다.

src/bin/where_clause.rs
use std::fmt::{Debug, Display};

// 경계가 여러 개면 + 로 잇는다
fn announce<T: Display + PartialOrd>(a: T, b: T) {
    if a >= b {
        println!("더 큰 쪽: {}", a);
    } else {
        println!("더 큰 쪽: {}", b);
    }
}

// 타입 매개변수와 경계가 많으면 where 로 따로 적는다
fn report<K, V>(key: K, value: V) -> String
where
    K: Display,
    V: Debug + Clone,
{
    let copy = value.clone();
    format!("{} = {:?}", key, copy)
}

fn main() {
    announce(37, 42);
    announce("사과", "배");
    println!("{}", report("점수", vec![90, 85]));
    println!("{}", report(1, ('가', true)));
}
$ cargo run --bin where_clause
   Compiling bounds v0.1.0 (…/p7/bounds)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/where_clause`
더 큰 쪽: 42
더 큰 쪽: 사과
점수 = [90, 85]
1 = ('가', true)

announce는 비교(PartialOrd)와 {} 출력(Display)이 모두 필요해서 두 경계를 붙였습니다. report의 V는 {:?}로 찍기 위해 Debug가, .clone()을 부르기 위해 Clone이 필요합니다. 경계에서 하나라도 빼 보면 그 기능을 쓴 줄에서 오류가 납니다.

3.3조건부로 생기는 메서드

impl 블록의 타입 매개변수에도 경계를 붙일 수 있습니다. 그러면 그 블록의 메서드는 T가 경계를 만족하는 Pair<T>에만 생깁니다.

src/bin/cond_impl.rs
use std::fmt::Display;

struct Pair<T> {
    first: T,
    second: T,
}

impl<T> Pair<T> {
    fn new(first: T, second: T) -> Self {
        Pair { first, second }
    }
}

// T 가 비교와 출력을 할 수 있을 때만 생기는 메서드
impl<T: PartialOrd + Display> Pair<T> {
    fn show_larger(&self) {
        if self.first >= self.second {
            println!("앞쪽이 크거나 같다: {}", self.first);
        } else {
            println!("뒤쪽이 크다: {}", self.second);
        }
    }
}

fn main() {
    Pair::new(70, 85).show_larger();
    Pair::new("하린", "민지").show_larger();
}
$ cargo run --bin cond_impl
   Compiling bounds v0.1.0 (…/p7/bounds)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/cond_impl`
뒤쪽이 크다: 85
앞쪽이 크거나 같다: 하린

new는 모든 Pair<T>에 있지만, show_larger는 비교와 출력이 되는 T일 때만 있습니다. 표준 라이브러리는 이 방법을 크게 씁니다. 예를 들어 "Display를 구현한 모든 타입에 ToString을 구현한다"는 일괄 구현(blanket implementation)이 있어서, Display만 구현하면 .to_string()이 저절로 생깁니다(5단원에서 확인합니다).

3.4impl Trait 반환

impl Trait는 반환 타입 자리에도 씁니다. "정확한 타입은 알려 주지 않지만 이 트레이트를 구현한 무언가를 돌려준다"는 뜻입니다. 호출한 쪽은 그 트레이트의 메서드만 쓸 수 있습니다.

src/bin/impl_ret.rs
// 돌려주는 값의 정확한 타입은 숨기고 "Fare 를 구현한 것"만 약속한다
fn commute(km: u32) -> impl Fare {
    Bus { km }
}

fn main() {
    let ride = commute(12);
    println!("{}: {}원", ride.name(), ride.fare());
}
$ cargo run --bin impl_ret
   Compiling bounds v0.1.0 (…/p7/bounds)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/impl_ret`
버스 12km: 1700원

이 표기는 9단계의 클로저·반복자처럼 타입 이름을 쓰기 어려운 값을 돌려줄 때 특히 쓸모가 있습니다. 한계도 있습니다. 함수가 돌려주는 실제 타입은 한 가지여야 합니다. 비가 오면 지하철, 아니면 버스를 돌려주려고 하면 오류가 납니다.

src/bin/ret_two.rs
fn commute(rainy: bool) -> impl Fare {
    if rainy { Subway } else { Bus }
}
$ cargo build --bin ret_two
   Compiling errs v0.1.0 (…/p7/errs)
error[E0308]: `if` and `else` have incompatible types
  --> src/bin/ret_two.rs:21:32
   |
21 |     if rainy { Subway } else { Bus }
   |                ------          ^^^ expected `Subway`, found `Bus`
   |                |
   |                expected because of this
   |
help: you could change the return type to be a boxed trait object
   |
20 - fn commute(rainy: bool) -> impl Fare {
20 + fn commute(rainy: bool) -> Box<dyn Fare> {
   |
help: if you change the return type to expect trait objects, box the returned expressions
   |
21 |     if rainy { Box::new(Subway) } else { Box::new(Bus) }
   |                +++++++++      +          +++++++++   +

For more information about this error, try `rustc --explain E0308`.
error: could not compile `errs` (bin "ret_two") due to 1 previous error

if와 else의 두 갈래 타입이 다르다는 E0308입니다. -> impl Fare는 숨겨진 실제 타입 하나를 뜻하므로 모든 갈래가 같은 타입을 돌려줘야 합니다. help가 Box<dyn Fare>로 바꾸라고 권하는데, 이것이 다음 단원의 주제인 트레이트 객체입니다.

핵심 정리
  • fn f(x: &impl Fare)와 fn f<T: Fare>(x: &T)는 거의 같은 뜻이며 둘 다 단형화된다.
  • 여러 경계는 T: A + B, 길면 where 절로 옮긴다.
  • 경계를 어긴 호출은 호출한 줄에서 E0277로 막힌다.
  • impl<T: 경계> 타입<T>로 조건부 메서드를 만들 수 있고, 표준 라이브러리의 일괄 구현도 같은 원리다.
  • -> impl Trait는 실제 타입 하나를 숨겨서 돌려준다. 여러 타입 중 하나를 돌려주려면 트레이트 객체가 필요하다.
참고 공식 책 10.2 Traits as Parameters, Returning Types That Implement Traits · Rust Reference "Impl trait" · rustc 오류 색인 E0277, E0308
4단원

트레이트 객체: dyn Trait

학습 목표
  • 서로 다른 타입을 Vec<Box<dyn Trait>> 하나에 담을 수 있다.
  • &dyn Trait가 데이터 포인터와 vtable 포인터로 이루어진 것을 설명할 수 있다.
  • 정적 디스패치와 동적 디스패치의 차이와 각각의 비용을 비교할 수 있다.
  • 모든 트레이트를 dyn으로 쓸 수 있는 것은 아니라는 것을 안다.

4.1제네릭으로는 안 되는 일

벡터는 한 가지 타입만 담으므로 Bus와 Subway를 섞으면 둘째 원소에서 E0308이 납니다.

src/bin/vec_mix.rs
fn main() {
    let today = vec![Bus { km: 3 }, Subway { stations: 9 }];
    println!("{}번 탐", today.len());
}
$ cargo build --bin vec_mix
   Compiling errs v0.1.0 (…/p7/errs)
error[E0308]: mismatched types
  --> src/bin/vec_mix.rs:10:37
   |
10 |     let today = vec![Bus { km: 3 }, Subway { stations: 9 }];
   |                                     ^^^^^^^^^^^^^^^^^^^^^^ expected `Bus`, found `Subway`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `errs` (bin "vec_mix") due to 1 previous error

제네릭 함수도 같은 한계가 있습니다. 하나의 T는 호출 한 번에 한 가지 타입입니다. 두 교통수단 중 싼 쪽의 요금을 구하려고 fn cheaper<T: Fare>(a: &T, b: &T)를 만들면, 버스와 지하철을 함께 넘길 수 없습니다.

src/bin/same_t.rs
// a 와 b 가 "같은" 타입 T 여야 한다
fn cheaper<T: Fare>(a: &T, b: &T) -> u32 {
    if a.fare() < b.fare() { a.fare() } else { b.fare() }
}

fn main() {
    println!("{}원", cheaper(&Bus, &Subway));
}
$ cargo build --bin same_t
   Compiling errs v0.1.0 (…/p7/errs)
error[E0308]: mismatched types
  --> src/bin/same_t.rs:26:35
   |
26 |     println!("{}원", cheaper(&Bus, &Subway));
   |                      -------       ^^^^^^^ expected `&Bus`, found `&Subway`
   |                      |
   |                      arguments to this function are incorrect
   |
   = note: expected reference `&Bus`
              found reference `&Subway`
note: function defined here
  --> src/bin/same_t.rs:21:4
   |
21 | fn cheaper<T: Fare>(a: &T, b: &T) -> u32 {
   |    ^^^^^^^                 -----

For more information about this error, try `rustc --explain E0308`.
error: could not compile `errs` (bin "same_t") due to 1 previous error

첫 인자로 T = Bus가 정해졌으니 둘째도 &Bus여야 한다는 메시지입니다. 3.1의 &impl Fare 두 개로 풀 수는 있지만, 개수가 정해지지 않은 벡터에는 통하지 않습니다.

4.2Box<dyn Trait>: 트레이트 객체

dyn Fare는 "Fare를 구현한 어떤 타입인지 컴파일할 때는 모르는 값"을 뜻하는 타입이고, 이런 값을 트레이트 객체(trait object)라고 부릅니다. 타입마다 크기가 다르므로 dyn Fare를 변수나 벡터에 그대로 담을 수는 없고, 언제나 포인터 뒤에 둡니다. 가장 흔한 두 모양이 &dyn Fare(빌린 것)와 Box<dyn Fare>(소유한 것)입니다. Box::new(값)은 값을 힙에 넣는 소유 포인터입니다(8단계에서 배웁니다).

src/bin/boxdyn.rs
fn main() {
    // 서로 다른 타입을 한 벡터에: 모두 Box<dyn Fare> 로 맞춘다
    let today: Vec<Box<dyn Fare>> = vec![
        Box::new(Subway { stations: 9 }),
        Box::new(Bus { km: 3 }),
        Box::new(Taxi { km: 4 }),
        Box::new(Subway { stations: 9 }),
    ];

    let mut sum = 0;
    for ride in &today {
        println!("{}: {}원", ride.name(), ride.fare());
        sum += ride.fare();
    }
    println!("합계 {}원 ({}번 탐)", sum, today.len());
}
$ cargo run --bin boxdyn
   Compiling dyns v0.1.0 (…/p7/dyns)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/boxdyn`
지하철 9개 역: 1500원
버스 3km: 1500원
택시 4km: 8800원
지하철 9개 역: 1500원
합계 13300원 (4번 탐)

벡터의 타입을 적어 두었기 때문에 각 Box::new(…)가 모두 Box<dyn Fare>로 바뀌어 들어갔습니다. 반복문 안의 ride.fare()는 원소마다 실제 타입의 메서드를 부릅니다. 같은 줄인데 어떤 때는 Subway::fare가, 어떤 때는 Taxi::fare가 실행되는 것입니다.

4.3&dyn 와 동적 디스패치

실행할 함수 몸통을 정하는 일을 디스패치(dispatch)라고 합니다. 제네릭과 impl Trait는 컴파일할 때 정하는 정적 디스패치(static dispatch), 트레이트 객체는 실행할 때 정하는 동적 디스패치(dynamic dispatch)입니다. 같은 일을 두 방식으로 해 보고, 포인터 크기도 재 봅니다.

src/bin/refdyn.rs
// 정적 디스패치: Bus 용, Subway 용 복사본이 따로 만들어진다
fn fare_static(item: &impl Fare) -> u32 {
    item.fare()
}

// 동적 디스패치: 함수는 하나, 실행할 때 표를 보고 메서드를 찾는다
fn fare_dynamic(item: &dyn Fare) -> u32 {
    item.fare()
}

fn main() {
    let bus = Bus { km: 25 };
    let subway = Subway { stations: 11 };

    println!("정적: {} {}", fare_static(&bus), fare_static(&subway));
    println!("동적: {} {}", fare_dynamic(&bus), fare_dynamic(&subway));

    println!("&Bus 크기      = {}바이트", size_of::<&Bus>());
    println!("&dyn Fare 크기 = {}바이트", size_of::<&dyn Fare>());
    println!("Box<dyn Fare>  = {}바이트", size_of::<Box<dyn Fare>>());
}
$ cargo run --bin refdyn
   Compiling dyns v0.1.0 (…/p7/dyns)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/refdyn`
정적: 3000 1600
동적: 3000 1600
&Bus 크기      = 8바이트
&dyn Fare 크기 = 16바이트
Box<dyn Fare>  = 16바이트

결과 값은 같고, 차이는 크기에서 보입니다. 이 64비트 컴퓨터에서 &Bus는 주소 하나라 8바이트인데, &dyn Fare와 Box<dyn Fare>는 16바이트로 두 배입니다. 트레이트 객체를 가리키는 포인터는 값의 주소와 그 타입의 vtable 주소를 함께 들고 다니기 때문입니다. 이런 포인터를 두꺼운 포인터(fat pointer)라고도 합니다. vtable은 타입마다 컴파일러가 하나씩 만들어 두는 표로, 그 타입의 트레이트 메서드 주소들(과 값을 버릴 때 필요한 정보, 크기 등)이 들어 있습니다.

&dyn Fare (16바이트) 값 주소 vtable 주소 Bus 값 km: 25 Bus 용 vtable 버리기·크기 정보 fare → Bus::fare item.fare() → vtable 에서 fare 칸을 읽어 그 주소로 뛴다
트레이트 객체 참조의 모양. vtable 안의 칸 배치는 컴파일러가 정하며 이 그림은 개념만 나타냅니다.

item.fare()는 vtable에서 fare 칸의 주소를 읽어 그리로 뜁니다. 이 간접 호출, 그리고 실행될 함수를 미리 몰라 인라인(inline) 같은 최적화가 어려워지는 것이 동적 디스패치의 비용입니다.

C와 비교

C로 "여러 종류의 교통수단"을 다루려면 흔히 구조체 안에 함수 포인터를 넣고(int (*fare)(const void *self);), 각 종류마다 그 포인터를 채운 표를 만들어 둡니다. Rust의 dyn Trait는 이 표(vtable)를 컴파일러가 자동으로 만들고, 표와 데이터가 서로 맞는지(Bus 값에 Taxi용 표가 붙는 일이 없는지)를 보장해 준다는 점이 다릅니다.

4.4무엇을 언제 쓸까, 그리고 dyn 호환

제네릭·impl Traitdyn Trait
타입이 정해지는 때컴파일할 때실행할 때
호출 방식직접 호출(인라인 가능)vtable을 거친 간접 호출
기계어 복사본타입마다 하나함수 하나
섞어 담기한 번에 한 타입여러 타입을 한 모음에

기본은 제네릭으로 쓰고, "실행해 봐야 어떤 타입들이 몇 개 올지 아는" 모음이 필요할 때 트레이트 객체를 쓰는 것이 일반적입니다. 플러그인 목록, 화면의 여러 위젯, 5단계에서 맛본 Box<dyn Error>(어떤 오류든 담는 상자)가 그런 예입니다.

모든 트레이트가 dyn으로 쓰일 수 있는 것은 아닙니다. vtable을 만들 수 있어야 하는데, 예를 들어 메서드가 Self(구현하는 타입 자신)를 값으로 돌려주면 실행할 때 그 크기를 알 수 없어서 vtable에 넣을 수 없습니다.

src/bin/not_dyn.rs
trait Ticket {
    fn price(&self) -> u32;
    fn renew(&self) -> Self;
}
$ cargo build --bin not_dyn
   Compiling errs v0.1.0 (…/p7/errs)
error[E0038]: the trait `Ticket` is not dyn compatible
  --> src/bin/not_dyn.rs:20:20
   |
20 |     let t: Box<dyn Ticket> = Box::new(Pass { days: 30 });
   |                    ^^^^^^ `Ticket` is not dyn compatible
   |
note: for a trait to be dyn compatible it needs to allow building a vtable
      for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
  --> src/bin/not_dyn.rs:3:24
   |
 1 | trait Ticket {
   |       ------ this trait is not dyn compatible...
 2 |     fn price(&self) -> u32;
 3 |     fn renew(&self) -> Self;
   |                        ^^^^ ...because method `renew` references the `Self` type in its return type
   = help: consider moving `renew` to another trait
   = help: only type `Pass` implements `Ticket`; consider using it directly instead.

For more information about this error, try `rustc --explain E0038`.
error: could not compile `errs` (bin "not_dyn") due to 1 previous error

E0038 메시지는 Ticket이 dyn 호환(dyn compatible)이 아니라고 말하고, 그 이유가 3번째 줄 renew의 반환 타입 Self라고 정확히 짚습니다. (예전 문서에서는 같은 개념을 object safety(객체 안전성)라고 불렀습니다.) 제네릭 메서드(fn f<T>(&self))가 있는 트레이트도 기본적으로 dyn이 될 수 없습니다. 타입마다 생길 복사본을 vtable 한 장에 다 적을 수 없기 때문입니다.

핵심 정리
  • 트레이트 객체 dyn Trait는 항상 포인터 뒤(&dyn, Box<dyn>)에 둔다. 서로 다른 타입을 한 모음에 담을 수 있다.
  • 트레이트 객체 포인터는 값 주소 + vtable 주소, 이 컴퓨터에서 16바이트다.
  • 제네릭은 정적 디스패치(컴파일할 때 결정), dyn은 동적 디스패치(실행할 때 vtable로 결정).
  • Self를 돌려주거나 제네릭 메서드가 있는 트레이트는 보통 dyn 호환이 아니다(E0038).
참고 공식 책 18장 Object-Oriented Programming Features 의 트레이트 객체 절 · Rust Reference "Trait objects", "Traits"의 Dyn compatibility · std 문서 std::mem::size_of · rustc 오류 색인 E0038
5단원

표준 트레이트: derive, Display, 연산자

학습 목표
  • derive 할 수 있는 표준 트레이트 아홉 가지가 각각 무엇을 가능하게 하는지 말할 수 있다.
  • derive 가 실패하는 경우(Copy와 Clone, String 필드, f64와 Eq)를 오류 메시지로 설명할 수 있다.
  • fmt::Display를 직접 구현해 {}로 찍히는 모양을 정할 수 있다.
  • std::ops::Add를 구현해 + 연산자를 내 타입에 쓸 수 있다.

5.1derive 할 수 있는 트레이트

4단계부터 써 온 #[derive(Debug)]는 "이 트레이트의 구현을 컴파일러가 대신 써 달라"는 표시입니다. 표준 라이브러리에서 derive 할 수 있는 트레이트는 다음과 같습니다.

트레이트생기는 것함께 있어야 할 것
Debug{:?}, {:#?} 출력—
Clone.clone()—
Copy대입·전달 때 이동 대신 복사Clone
PartialEq==, !=—
Eq"자기 자신과 늘 같다"는 표시PartialEq
PartialOrd<, >, <=, >=PartialEq
Ord완전한 순서, sort(), maxEq, PartialOrd
HashHashMap 키, HashSet 원소—
Default타입::default()—

어느 것이든 모든 필드가 그 트레이트를 구현해야 합니다. derive는 필드마다 그 기능을 불러 합치는 구현을 만들기 때문입니다. 아홉 가지를 모두 붙여 봅니다.

src/bin/derive.rs
use std::collections::HashSet;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(PartialOrd, Ord, Hash, Default)]
struct Seat {
    row: u8,
    col: u8,
}

fn main() {
    let a = Seat { row: 3, col: 7 };
    let b = a; // Copy: a 는 여전히 쓸 수 있다
    println!("a = {:?}, b = {:?}", a, b);
    println!("a == b ? {}", a == b);

    let mut seats = vec![
        Seat { row: 5, col: 1 },
        Seat { row: 2, col: 9 },
        Seat { row: 2, col: 3 },
    ];
    seats.sort(); // Ord: row 먼저, 같으면 col
    println!("정렬: {:?}", seats);

    let mut booked = HashSet::new(); // Hash + Eq
    booked.insert(a);
    booked.insert(b);
    println!("예약된 좌석 수: {}", booked.len());

    let empty = Seat::default(); // Default: 숫자는 0
    println!("기본값: {:?}", empty);
}
$ cargo run --bin derive
   Compiling stdt v0.1.0 (…/p7/stdt)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/derive`
a = Seat { row: 3, col: 7 }, b = Seat { row: 3, col: 7 }
a == b ? true
정렬: [Seat { row: 2, col: 3 }, Seat { row: 2, col: 9 }, Seat { row: 5, col: 1 }]
예약된 좌석 수: 1
기본값: Seat { row: 0, col: 0 }

Copy 덕분에 let b = a; 뒤에도 a를 쓰고, Ord로 sort()하고, Hash와 Eq로 HashSet에 넣었습니다(같은 좌석 두 번이라 크기 1).

5.2비교의 순서와 derive가 안 되는 경우

derive한 PartialOrd/Ord는 구조체라면 필드를 선언한 순서대로 비교하고(앞 필드가 다를 때 거기서 결론), 열거형이라면 먼저 적은 변형이 더 작습니다. Default는 수는 0, bool은 false, String은 빈 문자열로 채웁니다. 4단계의 구조체 갱신 문법 ..Default::default()와 함께 쓰면 일부 필드만 정하고 나머지를 기본값으로 둘 수 있습니다.

src/bin/enum_ord.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Grade {
    Bronze,
    Silver,
    Gold,
}

#[derive(Debug, Default)]
struct Member {
    name: String,
    visits: u32,
    vip: bool,
}

fn main() {
    // enum 은 위에 적은 변형이 더 작다
    println!("Gold > Silver ? {}", Grade::Gold > Grade::Silver);
    let mut list = vec![Grade::Gold, Grade::Bronze, Grade::Silver];
    list.sort();
    println!("{:?}", list);
    let higher = std::cmp::max(Grade::Silver, Grade::Bronze);
    println!("더 높은 쪽: {:?}", higher);

    // Default: String 은 빈 문자열, 수는 0, bool 은 false
    let m = Member::default();
    println!("{:?}", m);
    println!("이름 길이 {}, 방문 {}회", m.name.len(), m.visits);
    let n = Member {
        name: String::from("서준"),
        ..Default::default()
    };
    println!("{:#?}", n);
    println!("VIP? {}", n.vip);
}
$ cargo run --bin enum_ord
   Compiling stdt v0.1.0 (…/p7/stdt)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/enum_ord`
Gold > Silver ? true
[Bronze, Silver, Gold]
더 높은 쪽: Silver
Member { name: "", visits: 0, vip: false }
이름 길이 0, 방문 0회
Member {
    name: "서준",
    visits: 0,
    vip: false,
}
VIP? false

derive가 실패하는 대표적인 세 경우를 봅니다. 첫째, Copy만 붙이고 Clone을 빼먹은 경우입니다. Copy는 Clone을 먼저 구현해야 하는 트레이트라서 E0277이 나고, help가 #[derive(Clone)]을 더하라고 알려 줍니다.

src/bin/copy_only.rs
#[derive(Copy)]
struct Seat {
    row: u8,
    col: u8,
}
$ cargo build --bin copy_only
   Compiling errs v0.1.0 (…/p7/errs)
error[E0277]: the trait bound `Seat: Clone` is not satisfied
 --> src/bin/copy_only.rs:2:8
  |
1 | #[derive(Copy)]
  |          ---- in this derive macro expansion
2 | struct Seat {
  |        ^^^^ the trait `Clone` is not implemented for `Seat`
  |
note: required by a bound in `Copy`
 --> /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/marker.rs:454:0
help: consider annotating `Seat` with `#[derive(Clone)]`
  |
2 + #[derive(Clone)]
3 | struct Seat {
  |

For more information about this error, try `rustc --explain E0277`.
error: could not compile `errs` (bin "copy_only") due to 1 previous error

둘째, 힙의 자원을 소유한 String 필드가 있는 구조체는 Copy가 될 수 없습니다. 비트만 복사하면 두 값이 같은 힙 메모리를 가리키게 되어 3단계에서 배운 이중 해제 문제가 생기기 때문입니다. 이때는 E0204이고, 문제의 필드에 밑줄이 그어집니다.

src/bin/copy_string.rs
#[derive(Clone, Copy)]
struct Member {
    name: String,
    visits: u32,
}
$ cargo build --bin copy_string
   Compiling errs v0.1.0 (…/p7/errs)
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> src/bin/copy_string.rs:2:8
  |
1 | #[derive(Clone, Copy)]
  |                 ---- in this derive macro expansion
2 | struct Member {
  |        ^^^^^^
3 |     name: String,
  |     ------------ this field does not implement `Copy`

For more information about this error, try `rustc --explain E0204`.
error: could not compile `errs` (bin "copy_string") due to 1 previous error

셋째, f64 필드가 있으면 Eq를 derive할 수 없습니다. 실수에는 NaN(숫자가 아님)이라는 값이 있고 NaN == NaN은 false라서, "자기 자신과 늘 같다"는 Eq의 약속을 지키지 못하기 때문입니다. 같은 이유로 f64는 PartialOrd만 있고 Ord는 없습니다. 이름에 붙은 "Partial(부분적)"이 바로 이 뜻입니다.

src/bin/eq_float.rs
#[derive(PartialEq, Eq)]
struct Reading {
    place: String,
    celsius: f64,
}
$ cargo build --bin eq_float
   Compiling errs v0.1.0 (…/p7/errs)
error[E0277]: the trait bound `f64: Eq` is not satisfied
 --> src/bin/eq_float.rs:4:5
  |
1 | #[derive(PartialEq, Eq)]
  |                     -- in this derive macro expansion
...
4 |     celsius: f64,
  |     ^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64`
  |
  = help: the following other types implement trait `Eq`:
            i128
            i16
            i32
            i64
            i8
            isize
            u128
            u16
          and 4 others
note: required by a bound in `std::cmp::AssertParamIsEq`
 --> /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/cmp.rs:392:0

For more information about this error, try `rustc --explain E0277`.
error: could not compile `errs` (bin "eq_float") due to 1 previous error

5.3Display 직접 구현하기

{}로 찍는 Display는 사용자에게 보여 줄 모양이라 정답이 없으므로 derive가 없습니다. 구현하지 않고 {}를 쓰면 E0277이 나며, 메시지가 {:?}를 대신 권합니다.

src/bin/no_display.rs
struct Won(u64);

fn main() {
    let price = Won(4500);
    println!("가격: {}", price);
}
$ cargo build --bin no_display
   Compiling errs v0.1.0 (…/p7/errs)
error[E0277]: `Won` doesn't implement `std::fmt::Display`
 --> src/bin/no_display.rs:5:24
  |
5 |     println!("가격: {}", price);
  |                     --   ^^^^^ `Won` cannot be formatted with the default formatter
  |                     |
  |                     required by this formatting parameter
  |
help: the trait `std::fmt::Display` is not implemented for `Won`
 --> src/bin/no_display.rs:1:1
  |
1 | struct Won(u64);
  | ^^^^^^^^^^
  = note: in format strings you may be able to use `{:?}` (or `{:#?}` for pretty-print) instead

For more information about this error, try `rustc --explain E0277`.
error: could not compile `errs` (bin "no_display") due to 1 previous error

Display 트레이트에는 메서드가 fmt 하나 있습니다. 매개변수 f는 출력이 쌓이는 곳(Formatter)이고, 그 안에 write!(f, …)로 글자를 써 넣습니다. write!는 format!과 같은 형식 문자열을 받으며, 쓰기가 성공했는지를 fmt::Result로 돌려주므로 그대로 반환값으로 씁니다. 아래는 금액을 세 자리마다 쉼표를 찍어 보여 주는 Won 타입입니다.

src/bin/display.rs
use std::fmt;

struct Won(u64);

impl fmt::Display for Won {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // 세 자리마다 쉼표: 1234567 → 1,234,567
        let digits = self.0.to_string();
        let mut out = String::new();
        let mut left = digits.len(); // 아직 안 쓴 자릿수
        for ch in digits.chars() {
            out.push(ch);
            left -= 1;
            if left > 0 && left % 3 == 0 {
                out.push(',');
            }
        }
        write!(f, "{}원", out)
    }
}

fn main() {
    let rent = Won(650000);
    let coffee = Won(4500);
    println!("월세: {}", rent);
    println!("커피: {}", coffee);
    println!("큰돈: {}", Won(1234567890));

    let s: String = rent.to_string(); // Display 가 있으면 to_string 도 생긴다
    println!("글자 수: {}", s.chars().count());
}
$ cargo run --bin display
   Compiling stdt v0.1.0 (…/p7/stdt)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/display`
월세: 650,000원
커피: 4,500원
큰돈: 1,234,567,890원
글자 수: 8

마지막 두 줄은 3단원에서 말한 일괄 구현 덕분입니다. Display를 구현했으므로 to_string이 저절로 생겼습니다.

5.4연산자 오버로딩

a + b는 사실 std::ops::Add 트레이트의 add 메서드를 부르는 줄임 표현입니다. 그래서 내 타입에 Add를 구현하면 +를 쓸 수 있습니다. 이것을 연산자 오버로딩(operator overloading)이라고 합니다.

src/bin/add.rs
use std::fmt;
use std::ops::Add;

#[derive(Debug, Clone, Copy, PartialEq)]
struct Won(u64);

impl fmt::Display for Won {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}원", self.0)
    }
}

// Won + Won → Won
impl Add for Won {
    type Output = Won;

    fn add(self, other: Won) -> Won {
        Won(self.0 + other.0)
    }
}

fn main() {
    let lunch = Won(9000);
    let coffee = Won(4500);
    let total = lunch + coffee;
    println!("{} + {} = {}", lunch, coffee, total);
    println!("{}", total + Won(1500) + Won(1500));
    println!("같은가? {}", total == Won(13500));
}
$ cargo run --bin add
   Compiling stdt v0.1.0 (…/p7/stdt)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/add`
9000원 + 4500원 = 13500원
16500원
같은가? true

impl Add for Won 안의 type Output = Won;은 "더한 결과의 타입"을 정하는 연관 타입(associated type)입니다. 트레이트가 메서드뿐 아니라 타입도 하나 정해 달라고 요구하는 것이며, 9단계 Iterator의 type Item에서 다시 만납니다. add는 self를 값으로 받으므로 Won이 Copy가 아니면 lunch + coffee 뒤에 lunch를 쓸 수 없습니다. 이 예제는 Copy를 derive해서 그 문제를 피했습니다.

오른쪽 피연산자가 다른 타입이어도 됩니다. Add와 Mul은 사실 Add<Rhs = Self> 꼴의 제네릭 트레이트라서, impl Mul<f64> for Vec2처럼 오른쪽 타입을 정해 줄 수 있습니다.

src/bin/add_mixed.rs
use std::ops::{Add, Mul};

#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
    x: f64,
    y: f64,
}

// 벡터 + 벡터
impl Add for Vec2 {
    type Output = Vec2;
    fn add(self, o: Vec2) -> Vec2 {
        Vec2 { x: self.x + o.x, y: self.y + o.y }
    }
}

// 벡터 * 수: 오른쪽 타입을 f64 로 정한다
impl Mul<f64> for Vec2 {
    type Output = Vec2;
    fn mul(self, k: f64) -> Vec2 {
        Vec2 { x: self.x * k, y: self.y * k }
    }
}

fn main() {
    let walk = Vec2 { x: 1.0, y: 2.0 };
    let wind = Vec2 { x: 0.5, y: -0.5 };
    println!("{:?}", walk + wind);
    println!("{:?}", walk * 3.0);
    println!("{:?}", (walk + wind) * 2.0);
}
$ cargo run --bin add_mixed
   Compiling stdt v0.1.0 (…/p7/stdt)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/add_mixed`
Vec2 { x: 1.5, y: 1.5 }
Vec2 { x: 3.0, y: 6.0 }
Vec2 { x: 3.0, y: 3.0 }

규칙 두 가지를 기억해 둡시다. 첫째, std::ops와 std::cmp에 트레이트가 있는 연산자만 오버로딩할 수 있고 새 연산자를 만들 수는 없습니다. 둘째, +=는 Add가 아니라 AddAssign 트레이트가 따로 맡습니다. 고아 규칙도 그대로 적용됩니다.

핵심 정리
  • derive 가능한 표준 트레이트: Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default. 모든 필드가 그 트레이트를 구현해야 한다.
  • Copy는 Clone이 필요하고, String 같은 소유 필드가 있으면 불가능하다(E0204). f64는 Eq·Ord가 없다.
  • derive된 비교는 필드 선언 순서, 열거형은 변형을 적은 순서를 따른다.
  • Display는 직접 fmt를 구현하며, 구현하면 to_string이 따라온다.
  • impl Add for T { type Output = …; fn add(self, …) }로 +를 정의한다. +=는 AddAssign.
참고 공식 책 부록 C Derivable Traits · std 문서 std::fmt::Display, std::ops::Add, std::cmp::Ord, std::marker::Copy · rustc 오류 색인 E0204

5.5연습문제

1. 1단원의 largest를 본떠 가장 작은 원소의 참조를 돌려주는 제네릭 함수 smallest를 만들고 실수, 문자열, 정수 배열로 확인하세요.

풀이 보기

비교 방향만 <로 바꾸면 됩니다. 경계는 그대로 PartialOrd입니다. 한글 "귤"이 "배", "사과"보다 코드값이 작습니다.

src/bin/ex1.rs
fn smallest<T: PartialOrd>(list: &[T]) -> &T {
    let mut low = &list[0];
    for item in list {
        if item < low {
            low = item;
        }
    }
    low
}

fn main() {
    println!("{}", smallest(&[3.5, 1.25, 2.0]));
    println!("{}", smallest(&["사과", "귤", "배"]));
    println!("{}", smallest(&[40, 15, 99]));
}
$ cargo run --bin ex1
   Compiling ex v0.1.0 (…/p7/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex1`
1.25
귤
15

2. 도서관 대출물 트레이트 Loan을 만드세요. title은 반드시 구현해야 하고, late_fee(&self, days: u32) -> u32는 하루 100원으로 계산하는 기본 구현을 둡니다. Book은 기본 구현을 쓰고, Dvd는 하루 500원으로 덮어쓰세요.

풀이 보기

기본 구현이 있는 메서드는 impl Loan for Book에서 생략했습니다.

src/bin/ex2.rs
trait Loan {
    fn title(&self) -> String;

    // 기본: 하루 늦을 때마다 100원
    fn late_fee(&self, days: u32) -> u32 {
        days * 100
    }
}

struct Book {
    name: String,
}

struct Dvd {
    name: String,
}

impl Loan for Book {
    fn title(&self) -> String {
        format!("책 「{}」", self.name)
    }
}

impl Loan for Dvd {
    fn title(&self) -> String {
        format!("DVD 「{}」", self.name)
    }

    fn late_fee(&self, days: u32) -> u32 {
        days * 500
    }
}

fn main() {
    let b = Book { name: String::from("어린 왕자") };
    let d = Dvd { name: String::from("자연 다큐") };
    println!("{}: {}원", b.title(), b.late_fee(3));
    println!("{}: {}원", d.title(), d.late_fee(3));
}
$ cargo run --bin ex2
   Compiling ex v0.1.0 (…/p7/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex2`
책 「어린 왕자」: 300원
DVD 「자연 다큐」: 1500원

3. 2번의 책 두 권과 DVD 하나를 Vec<Box<dyn Loan>>에 담고, 슬라이스를 받아 연체료 합계를 돌려주는 함수 total_fee를 만드세요.

풀이 보기

&Vec<Box<dyn Loan>>는 &[Box<dyn Loan>]로 자동 변환되므로 매개변수를 슬라이스로 받았습니다. 300 + 1500 + 300 = 2100원입니다.

src/bin/ex3.rs
fn total_fee(items: &[Box<dyn Loan>], days: u32) -> u32 {
    let mut sum = 0;
    for item in items {
        sum += item.late_fee(days);
    }
    sum
}

fn main() {
    let bag: Vec<Box<dyn Loan>> = vec![
        Box::new(Book { name: String::from("어린 왕자") }),
        Box::new(Dvd { name: String::from("자연 다큐") }),
        Box::new(Book { name: String::from("코스모스") }),
    ];
    for item in &bag {
        println!("{}", item.title());
    }
    println!("3일 연체료 합계: {}원", total_fee(&bag, 3));
}
$ cargo run --bin ex3
   Compiling ex v0.1.0 (…/p7/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex3`
책 「어린 왕자」
DVD 「자연 다큐」
책 「코스모스」
3일 연체료 합계: 2100원

4. 섭씨온도 struct Celsius(f64);에 Display를 구현해서 0 이상이면 섭씨 23.5도, 0 미만이면 영하 7도처럼 찍히게 하세요. to_string()도 확인하세요.

풀이 보기

-7.0을 부호를 뒤집어 7.0으로 찍으면 소수 부분이 0이라 7로 보입니다.

src/bin/ex4.rs
use std::fmt;

struct Celsius(f64);

impl fmt::Display for Celsius {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.0 < 0.0 {
            write!(f, "영하 {}도", -self.0)
        } else {
            write!(f, "섭씨 {}도", self.0)
        }
    }
}

fn main() {
    println!("{}", Celsius(23.5));
    println!("{}", Celsius(-7.0));
    let s = Celsius(0.5).to_string();
    println!("[{}]", s);
}
$ cargo run --bin ex4
   Compiling ex v0.1.0 (…/p7/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex4`
섭씨 23.5도
영하 7도
[섭씨 0.5도]

5. 시간과 분을 담는 Duration 구조체에 Add와 Display를 구현하세요. 분이 60을 넘으면 시간으로 올립니다. 1시간 50분 + 20분 = 2시간 10분이 되어야 하고, ==로 비교할 수 있어야 합니다.

풀이 보기

==는 derive한 PartialEq, 덧셈 뒤에도 study와 review를 쓰기 위해 Copy를 derive했습니다.

src/bin/ex5.rs
use std::fmt;
use std::ops::Add;

#[derive(Debug, Clone, Copy, PartialEq)]
struct Duration {
    hours: u32,
    minutes: u32,
}

impl Add for Duration {
    type Output = Duration;

    fn add(self, other: Duration) -> Duration {
        let total = self.minutes + other.minutes;
        Duration {
            hours: self.hours + other.hours + total / 60,
            minutes: total % 60,
        }
    }
}

impl fmt::Display for Duration {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}시간 {}분", self.hours, self.minutes)
    }
}

fn main() {
    let study = Duration { hours: 1, minutes: 50 };
    let review = Duration { hours: 0, minutes: 20 };
    let sum = study + review;
    println!("{} + {} = {}", study, review, sum);
    println!("{}", sum == Duration { hours: 2, minutes: 10 });
}
$ cargo run --bin ex5
   Compiling ex v0.1.0 (…/p7/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex5`
1시간 50분 + 0시간 20분 = 2시간 10분
true