$ cargo run --stage 4

4단계: 구조체와 열거형 강의 노트

구조체로 여러 값을 하나의 타입으로 묶고 impl 로 메서드와 연관 함수를 붙입니다. 열거형으로 '여러 경우 중 하나'를 나타내고, Option 으로 null 없이 '없음'을 다루며, match·if let·let else·while let·matches! 로 모든 경우를 빠짐없이 처리하는 규칙을 정확히 익힙니다.

기간 13~16주구성 5개 단원
1단원

구조체: 여러 값을 하나의 이름으로 묶기

학습 목표
  • 이름 붙은 필드를 가진 구조체(struct)를 정의하고 인스턴스를 만들어 필드를 읽고 고칠 수 있다.
  • 필드 초기화 단축 문법과 구조체 갱신 문법을 쓰고, 갱신 문법에서 일어나는 이동을 설명할 수 있다.
  • 튜플 구조체와 유닛 구조체가 언제 쓸모 있는지 말할 수 있다.

1.1정의하고, 만들고, 읽기

지금까지는 값 하나에 변수 하나를 썼습니다. 그런데 도서관 책 한 권만 해도 제목, 지은이, 출판 연도, 서가에 있는지 여부처럼 여러 정보가 함께 다닙니다. 튜플 (String, String, u16, bool) 로 묶을 수도 있지만, book.2 가 연도인지 쪽수인지는 코드만 봐서는 알 수 없습니다. 구조체(struct) 는 각 칸에 필드(field) 라는 이름과 타입을 붙여서 새 타입을 만드는 방법입니다.

src/bin/book.rs
// 도서관 책 한 권을 구조체로 나타낸다
struct Book {
    title: String,
    author: String,
    year: u16,
    on_shelf: bool,
}

fn main() {
    let mut book = Book {
        title: String::from("어린 왕자"),
        author: String::from("생텍쥐페리"),
        year: 1943,
        on_shelf: true,
    };

    println!("{} ({}, {}년)", book.title, book.author, book.year);
    println!("서가에 있음: {}", book.on_shelf);

    // 대출: 필드 하나만 바꾼다 (book 이 mut 이어야 한다)
    book.on_shelf = false;
    println!("대출 후 서가에 있음: {}", book.on_shelf);
}
  • struct Book { … } 은 타입의 설계도입니다. 필드마다 이름: 타입 을 쉼표로 이어 적습니다. 타입 이름은 Book 처럼 대문자로 시작하는 낙타 표기(CamelCase)를 씁니다.
  • Book { title: …, author: …, … } 는 설계도대로 실제 값을 하나 만드는 인스턴스(instance) 생성 표현식입니다. 모든 필드에 값을 주어야 하며, 적는 순서는 정의 순서와 달라도 됩니다.
  • 필드는 book.title 처럼 점(.)으로 읽고, book.on_shelf = false; 처럼 고칩니다.
$ cargo run --bin book
   Compiling structs v0.1.0 (…/p4/structs)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/book`
어린 왕자 (생텍쥐페리, 1943년)
서가에 있음: true
대출 후 서가에 있음: false

필드 하나를 고치려면 인스턴스 전체가 let mut 이어야 합니다. Rust 에는 "이 필드만 가변" 같은 표시가 없습니다. 가변성은 값이 아니라 그 값을 가진 변수(바인딩) 에 붙는 성질이기 때문입니다. mut 을 빼면 이렇게 됩니다.

src/bin/field_immut.rs
struct Book {
    title: String,
    on_shelf: bool,
}

fn main() {
    let book = Book {
        title: String::from("코스모스"),
        on_shelf: true,
    };
    book.on_shelf = false;
    println!("{} {}", book.title, book.on_shelf);
}
$ cargo build -q --bin field_immut
error[E0594]: cannot assign to `book.on_shelf`, as `book` is not declared as mutable
  --> src/bin/field_immut.rs:11:5
   |
11 |     book.on_shelf = false;
   |     ^^^^^^^^^^^^^^^^^^^^^ cannot assign
   |
help: consider changing this to be mutable
   |
 7 |     let mut book = Book {
   |         +++

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

첫 줄의 error[E0594] 가 오류 번호이고, --> src/bin/field_immut.rs:11:5 는 11번째 줄 5번째 글자를 가리킵니다. ^^^ 밑줄이 문제의 대입문이고, help 아래 +++ 는 "7번째 줄 let 뒤에 mut 을 넣으라"는 제안입니다.

1.2필드 초기화 단축과 갱신 문법

함수에서 인스턴스를 만들어 돌려줄 때 매개변수 이름과 필드 이름이 같은 경우가 많습니다. 이때는 name: name 대신 name 만 적어도 됩니다. 이것을 필드 초기화 단축(field init shorthand) 이라고 합니다.

src/bin/shorthand.rs
struct Member {
    name: String,
    age: u8,
    points: u32,
}

// 매개변수 이름이 필드 이름과 같으면 `name: name` 을 `name` 으로 줄인다
fn join(name: String, age: u8) -> Member {
    Member { name, age, points: 0 }
}

fn main() {
    let m = join(String::from("김하늘"), 17);
    println!("{} / {}살 / {}점", m.name, m.age, m.points);
}
$ cargo run -q --bin shorthand
김하늘 / 17살 / 0점

이미 있는 인스턴스와 거의 같은데 몇 필드만 다른 새 인스턴스가 필요할 때는 구조체 갱신 문법(struct update syntax) ..기존값 을 씁니다. 직접 적은 필드는 새 값으로, 적지 않은 나머지 필드는 .. 뒤의 인스턴스에서 가져옵니다. ..base 는 반드시 중괄호 안 맨 끝에 와야 합니다.

src/bin/update.rs
struct Settings {
    nickname: String,
    volume: u8,
    dark_mode: bool,
    font_size: u8,
}

fn main() {
    let base = Settings {
        nickname: String::from("기본"),
        volume: 50,
        dark_mode: false,
        font_size: 14,
    };

    // dark_mode 만 다르고 나머지는 base 에서 가져온다
    let night = Settings {
        dark_mode: true,
        ..base
    };

    println!("{} {} {} {}", night.nickname, night.volume,
             night.dark_mode, night.font_size);

    // nickname(String)은 night 로 이동했지만
    // Copy 타입 필드는 복사됐으므로 아직 쓸 수 있다
    println!("base.volume = {}", base.volume);
}
$ cargo run -q --bin update
기본 50 true 14
base.volume = 50

여기서 "가져온다"는 말은 3단계에서 배운 대입과 같은 규칙을 따른다는 뜻입니다. volume, font_size(u8)처럼 Copy 타입인 필드는 복사되고, nickname(String)은 이동(move) 합니다. 그래서 갱신 뒤에도 base.volume 은 쓸 수 있지만 base.nickname 은 쓸 수 없습니다.

src/bin/update_move.rs
struct Settings {
    nickname: String,
    volume: u8,
    dark_mode: bool,
}

fn main() {
    let base = Settings {
        nickname: String::from("기본"),
        volume: 50,
        dark_mode: false,
    };
    let night = Settings { dark_mode: true, ..base };
    println!("{} {}", night.nickname, night.volume);
    println!("{}", base.nickname);
}
$ cargo build -q --bin update_move
error[E0382]: borrow of moved value: `base.nickname`
  --> src/bin/update_move.rs:15:20
   |
13 |     let night = Settings { dark_mode: true, ..base };
   |                 ------------------------------------ value moved here
14 |     println!("{} {}", night.nickname, night.volume);
15 |     println!("{}", base.nickname);
   |                    ^^^^^^^^^^^^^ value borrowed here after move
   |
   = note: move occurs because `base.nickname` has type `String`, which does not implement the `Copy` trait

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

메시지가 `base` 가 아니라 `base.nickname` 을 콕 집어 말하는 데 주목하세요. 빌림 검사기(borrow checker)는 구조체를 필드 단위로 추적합니다. base 는 일부만 이동한(partially moved) 상태라서, 이동한 필드와 base 전체는 못 쓰고 남은 필드는 쓸 수 있습니다. 만약 nickname 까지 직접 새 값으로 적었다면 base 에서 이동하는 필드가 없으니 base 를 계속 통째로 쓸 수 있습니다.

base night nickname (이동함) volume 50 dark_mode false font_size 14 nickname "기본" volume 50 dark_mode true font_size 14 이동 복사 복사 직접 적은 새 값
그림 4-1. Settings { dark_mode: true, ..base }. String 필드는 옮겨 가고, Copy 필드는 복사되며, 직접 적은 필드는 base 에서 가져오지 않습니다.

1.3튜플 구조체와 유닛 구조체

필드에 이름을 붙일 만큼 의미가 뚜렷하지 않거나, 값 하나를 감싸 다른 타입으로 구별하고 싶을 때는 튜플 구조체(tuple struct) 를 씁니다. 필드는 이름 대신 .0, .1 같은 번호로 읽습니다.

src/bin/tuple.rs
// 이름 없는 필드 셋을 가진 튜플 구조체
struct Rgb(u8, u8, u8);

// 같은 f64 하나를 담지만 서로 다른 타입이다
struct Celsius(f64);
struct Fahrenheit(f64);

fn to_fahrenheit(c: Celsius) -> Fahrenheit {
    Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}

fn main() {
    let pink = Rgb(255, 192, 203);
    println!("빨강 {}, 초록 {}, 파랑 {}", pink.0, pink.1, pink.2);

    // 튜플처럼 풀어서 이름을 붙일 수도 있다
    let Rgb(r, g, b) = pink;
    println!("합계 {}", r as u32 + g as u32 + b as u32);

    let today = Celsius(36.5);
    let f = to_fahrenheit(today);
    println!("섭씨 36.5도 = 화씨 {:.1}도", f.0);
}
$ cargo run -q --bin tuple
빨강 255, 초록 192, 파랑 203
합계 650
섭씨 36.5도 = 화씨 97.7도

Celsius 와 Fahrenheit 는 속에 똑같이 f64 하나를 담지만 컴파일러에게는 전혀 다른 타입입니다. 섭씨를 받아야 하는 함수에 화씨를 넘기면 실행하기 전에 막힙니다. 단위를 헷갈리는 실수를 타입으로 막는 이런 방식을 흔히 뉴타입(newtype) 기법이라고 부릅니다.

src/bin/celsius.rs
struct Celsius(f64);
struct Fahrenheit(f64);

fn is_fever(c: Celsius) -> bool {
    c.0 >= 37.5
}

fn main() {
    let t = Fahrenheit(99.5);
    println!("{}", is_fever(t));
}
$ cargo build -q --bin celsius
error[E0308]: mismatched types
  --> src/bin/celsius.rs:10:29
   |
10 |     println!("{}", is_fever(t));
   |                    -------- ^ expected `Celsius`, found `Fahrenheit`
   |                    |
   |                    arguments to this function are incorrect
   |
note: function defined here
  --> src/bin/celsius.rs:4:4
   |
 4 | fn is_fever(c: Celsius) -> bool {
   |    ^^^^^^^^ ----------

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

expected `Celsius`, found `Fahrenheit` 가 핵심이고, note 는 함수가 정의된 4번째 줄을 보여 줍니다.

필드가 아예 없는 구조체도 있습니다. struct Silent; 처럼 이름만 있고 중괄호도 괄호도 없는 이것을 유닛 구조체(unit struct) 라고 합니다. 담는 데이터는 없지만 메서드를 붙일 수 있고, 7단계에서 배울 트레이트를 구현하는 "표지"로 쓰입니다.

src/bin/unit.rs
// 필드가 하나도 없는 유닛 구조체
struct Silent;

impl Silent {
    fn speak(&self) {
        println!("(아무 말도 하지 않습니다)");
    }
}

fn main() {
    let s = Silent;
    s.speak();
    println!("Silent 의 크기: {}바이트", std::mem::size_of::<Silent>());
}
$ cargo run -q --bin unit
(아무 말도 하지 않습니다)
Silent 의 크기: 0바이트

std::mem::size_of::<타입>() 는 그 타입의 값이 메모리에서 차지하는 바이트 수를 알려 주는 표준 함수입니다. 유닛 구조체는 담을 것이 없어서 0바이트입니다. (impl 과 &self 는 2단원에서 자세히 봅니다.)

1.4구조체는 메모리에서 어떻게 생겼나

구조체 값은 필드들을 한 덩어리로 이어 붙인 것입니다. let book = Book { … } 처럼 지역 변수로 만들면 덩어리 전체가 스택에 놓입니다. 다만 String 필드는 3단계에서 본 대로 (포인터, 길이, 용량) 세 칸만 구조체 안에 있고, 실제 글자 바이트는 힙에 있습니다. 구조체는 필드를 소유하므로, 스코프를 벗어나면 각 String 의 힙 메모리도 함께 해제됩니다.

스택: book 힙 title 포인터 · 길이 · 용량 author 포인터 · 길이 · 용량 1943 true "어린 왕자" 바이트 "생텍쥐페리" 바이트
그림 4-2. 지역 변수 book 의 모습(개념도). 실제 필드 배치 순서와 틈은 컴파일러가 정하며, 정의한 순서와 같다고 보장되지 않습니다.
C와 비교

C의 struct 와 닮았지만, C에서는 struct book b; 처럼 struct 를 붙이거나 typedef 를 써야 하는 반면 Rust 에서는 Book 이 곧 타입 이름입니다. C는 필드를 초기화하지 않은 채 둘 수 있지만 Rust 는 모든 필드에 값이 있어야 컴파일합니다. 또 C 구조체는 필드를 선언 순서대로 배치하지만, Rust 의 기본 배치는 순서를 보장하지 않아 컴파일러가 틈을 줄이도록 재배치할 수 있습니다. 무엇보다 C 구조체 안의 char * 는 누가 free 할지 프로그래머가 기억해야 하지만, Rust 구조체 안의 String 은 구조체가 사라질 때 자동으로 정리됩니다.

핵심 정리
  • struct 이름 { 필드: 타입, … } 으로 정의하고 이름 { 필드: 값, … } 으로 인스턴스를 만든다. 모든 필드에 값이 필요하다.
  • 필드를 고치려면 인스턴스 전체가 mut 이어야 한다(E0594).
  • 필드 초기화 단축: name: name → name. 갱신 문법 ..base 는 맨 끝에 오고, 이동 규칙을 그대로 따른다.
  • 튜플 구조체는 번호로 접근하며 같은 속 타입이라도 서로 다른 타입이다. 유닛 구조체는 필드가 없다.
참고 The Rust Programming Language 5장 · The Rust Reference "Structs", "Struct expressions" · std::mem::size_of 문서
2단원

디버그 출력과 메서드

학습 목표
  • #[derive(Debug)] 를 붙여 구조체를 {:?}, {:#?} 로 출력할 수 있다.
  • impl 블록에 메서드를 정의하고 &self, &mut self, self 를 상황에 맞게 고를 수 있다.
  • 연관 함수와 Self 를 써서 생성 함수 new 를 만들 수 있다.

2.1#[derive(Debug)] 와 {:?}·{:#?}

정수나 String 은 {} 로 바로 출력됩니다. 하지만 우리가 만든 구조체를 어떤 모양으로 보여 줄지는 Rust 가 알 수 없습니다. 개발 중에 속을 들여다보는 용도라면 구조체 위에 #[derive(Debug)] 한 줄을 붙이면 됩니다. 이것은 속성(attribute) 으로, 컴파일러에게 "디버그용 출력 코드를 대신 만들어 달라"고 부탁합니다.

src/bin/debug.rs
#[derive(Debug)]
struct Date {
    year: u16,
    month: u8,
    day: u8,
}

#[derive(Debug)]
struct Loan {
    title: String,
    due: Date,
}

fn main() {
    let loan = Loan {
        title: String::from("코스모스"),
        due: Date { year: 2026, month: 11, day: 12 },
    };

    println!("{:?}", loan);   // 한 줄로
    println!("{:#?}", loan);  // 여러 줄로 보기 좋게
    println!("《{}》 반납일: {}년 {}월 {}일", loan.title,
             loan.due.year, loan.due.month, loan.due.day);
}
$ cargo run -q --bin debug
Loan { title: "코스모스", due: Date { year: 2026, month: 11, day: 12 } }
Loan {
    title: "코스모스",
    due: Date {
        year: 2026,
        month: 11,
        day: 12,
    },
}
《코스모스》 반납일: 2026년 11월 12일

{:?} 는 한 줄로, {:#?} 는 필드마다 줄을 바꾸고 들여 써서 보여 줍니다. 구조체 안에 구조체가 있을 때는 안쪽 타입(Date)에도 Debug 가 있어야 합니다. 문자열 필드는 따옴표로 둘러싸여 나오는 점도 눈여겨보세요. 사용자에게 보여 줄 깔끔한 모양({})을 직접 정하는 Display 구현은 7단계에서 배웁니다.

derive 를 빼먹으면 다음과 같은 오류가 납니다. Debug 는 트레이트(trait) 라는 것인데, 지금은 "타입이 할 줄 아는 능력의 이름" 정도로 이해하면 충분합니다(7단계에서 자세히 배웁니다). 컴파일러가 help 에서 붙일 줄까지 정확히 알려 줍니다.

src/bin/no_debug.rs
struct Date {
    year: u16,
    month: u8,
    day: u8,
}

fn main() {
    let d = Date { year: 2026, month: 11, day: 12 };
    println!("{:?}", d);
}
$ cargo build -q --bin no_debug
error[E0277]: `Date` doesn't implement `Debug`
 --> src/bin/no_debug.rs:9:22
  |
9 |     println!("{:?}", d);
  |               ----   ^ `Date` cannot be formatted using `{:?}` because it doesn't implement `Debug`
  |               |
  |               required by this formatting parameter
  |
  = help: the trait `Debug` is not implemented for `Date`
help: consider annotating `Date` with `#[derive(Debug)]`
  |
1 + #[derive(Debug)]
2 | struct Date {
  |

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

2.2impl 과 세 가지 self

구조체에 딸린 함수를 impl 타입 { … } 블록 안에 정의할 수 있습니다. 첫 매개변수가 self 인 함수를 메서드(method) 라고 하며, 값.메서드() 꼴로 부릅니다. 아래는 가계부 통장을 흉내 낸 예입니다.

src/bin/account.rs
#[derive(Debug)]
struct Account {
    owner: String,
    balance: i64,
    count: u32, // 거래 횟수
}

impl Account {
    // 연관 함수: self 가 없다. Account::new(...) 로 부른다
    fn new(owner: &str) -> Self {
        Self { owner: String::from(owner), balance: 0, count: 0 }
    }

    // &self: 읽기만 한다
    fn balance(&self) -> i64 {
        self.balance
    }

    // &mut self: 고친다
    fn deposit(&mut self, amount: i64) {
        self.balance += amount;
        self.count += 1;
    }

    fn withdraw(&mut self, amount: i64) -> bool {
        if amount > self.balance {
            return false;
        }
        self.balance -= amount;
        self.count += 1;
        true
    }

    // self: 값을 통째로 가져간다. 부른 뒤에는 계좌를 쓸 수 없다
    fn close(self) -> i64 {
        println!("{} 님 계좌 해지 (거래 {}번)", self.owner, self.count);
        self.balance
    }
}

fn main() {
    let mut acc = Account::new("박서준");
    acc.deposit(30_000);
    acc.deposit(12_000);
    let ok = acc.withdraw(50_000);
    println!("5만 원 출금 성공? {}", ok);
    let ok = acc.withdraw(8_000);
    println!("8천 원 출금 성공? {}", ok);
    println!("잔액: {}원", acc.balance());
    println!("{:?}", acc);

    let left = acc.close();
    println!("돌려받은 돈: {}원", left);
}
$ cargo run -q --bin account
5만 원 출금 성공? false
8천 원 출금 성공? true
잔액: 34000원
Account { owner: "박서준", balance: 34000, count: 3 }
박서준 님 계좌 해지 (거래 3번)
돌려받은 돈: 34000원

첫 매개변수의 모양에 따라 메서드가 값을 어떻게 다루는지가 정해집니다. 3단계에서 배운 빌림 규칙이 그대로 적용됩니다.

첫 매개변수뜻 (줄이기 전 모양)할 수 있는 일예
&selfself: &Self 불변 빌림읽기만balance
&mut selfself: &mut Self 가변 빌림필드 고치기deposit, withdraw
selfself: Self 소유권 가져오기값을 써서 없애거나 다른 것으로 바꾸기close

Self 는 "지금 impl 하고 있는 타입"의 별명으로, 여기서는 Account 와 같습니다. 고르는 기준은 간단합니다. 읽기만 하면 &self, 고쳐야 하면 &mut self, 부른 뒤 원래 값을 더 쓰면 안 되는 일(해지, 변환)이면 self 입니다. 가장 흔한 것은 &self 입니다.

메서드 이름이 필드 이름과 같아도 됩니다. acc.balance() 는 메서드, 괄호 없는 acc.balance 는 필드입니다.

&mut self 메서드는 변수가 mut 이어야 부를 수 있습니다. 메서드 호출이 곧 &mut c 를 만드는 일이기 때문입니다.

src/bin/not_mut.rs
struct Counter {
    count: u32,
}

impl Counter {
    fn tick(&mut self) {
        self.count += 1;
    }
}

fn main() {
    let c = Counter { count: 0 };
    c.tick();
    println!("{}", c.count);
}
$ cargo build -q --bin not_mut
error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable
  --> src/bin/not_mut.rs:13:5
   |
13 |     c.tick();
   |     ^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
12 |     let mut c = Counter { count: 0 };
   |         +++

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

self 를 받는 메서드를 부르면 값이 이동하므로 그 뒤에는 변수를 쓸 수 없습니다.

src/bin/after_close.rs
struct Account {
    balance: i64,
}

impl Account {
    fn close(self) -> i64 {
        self.balance
    }
}

fn main() {
    let acc = Account { balance: 5_000 };
    let left = acc.close();
    println!("{}", left);
    println!("{}", acc.balance);
}
$ cargo build -q --bin after_close
error[E0382]: borrow of moved value: `acc`
  --> src/bin/after_close.rs:15:20
   |
12 |     let acc = Account { balance: 5_000 };
   |         --- move occurs because `acc` has type `Account`, which does not implement the `Copy` trait
13 |     let left = acc.close();
   |                    ------- `acc` moved due to this method call
14 |     println!("{}", left);
15 |     println!("{}", acc.balance);
   |                    ^^^^^^^^^^^ value borrowed here after move
   |
note: `Account::close` takes ownership of the receiver `self`, which moves `acc`
  --> src/bin/after_close.rs:6:14
   |
 6 |     fn close(self) -> i64 {
   |              ^^^^

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

2.3연관 함수와 new

impl 블록 안에 있지만 첫 매개변수가 self 가 아닌 함수를 연관 함수(associated function) 라고 합니다. 특정 인스턴스 없이 타입에 딸려 있으므로 타입::함수() 꼴, 즉 점이 아니라 :: 로 부릅니다. 3단계에서 쓴 String::from 도 연관 함수입니다. 가장 흔한 용도는 인스턴스를 만들어 돌려주는 생성 함수이고, 관례적으로 new 라는 이름을 씁니다. new 는 예약어가 아니라 그냥 관례라서, 아래처럼 뜻이 드러나는 다른 이름도 자유롭게 씁니다.

src/bin/assoc.rs
#[derive(Debug)]
struct Timer {
    seconds: u32,
}

impl Timer {
    fn zero() -> Self {
        Timer { seconds: 0 }
    }

    fn from_minutes(m: u32) -> Self {
        Timer { seconds: m * 60 }
    }
}

// impl 블록은 여러 개로 나눠도 된다
impl Timer {
    fn add(&mut self, s: u32) {
        self.seconds += s;
    }

    fn minutes(&self) -> u32 {
        self.seconds / 60
    }
}

fn main() {
    let mut t = Timer::zero();
    t.add(90);
    println!("{:?} → {}분", t, t.minutes());

    let mut u = Timer::from_minutes(3);
    // 아래 두 줄은 같은 일을 한다
    u.add(30);
    Timer::add(&mut u, 30);
    println!("{:?} → {}분", u, Timer::minutes(&u));
}
$ cargo run -q --bin assoc
Timer { seconds: 90 } → 1분
Timer { seconds: 240 } → 4분

세 가지를 더 볼 수 있습니다. 첫째, impl Timer 블록을 여러 개로 나눠도 됩니다. 둘째, u.add(30) 과 Timer::add(&mut u, 30) 은 완전히 같은 호출입니다. 셋째, 점 표기로 부를 때는 컴파일러가 메서드의 첫 매개변수에 맞춰 &, &mut 을 자동으로 붙여 줍니다. 그래서 u.add(30) 이라고만 써도 &mut u 가 넘어갑니다.

왜 이렇게 만들었을까

Rust 에는 다른 언어의 "생성자" 같은 특별한 문법이 없습니다. 인스턴스를 만드는 길은 언제나 Timer { seconds: … } 같은 구조체 표현식 하나뿐이고, new 나 from_minutes 는 그 표현식을 감싼 평범한 함수입니다. 특별한 규칙이 없으니 이름도 매개변수도 개수도 자유롭고, 실패할 수 있는 생성은 5단계의 Result 를 돌려주면 됩니다.

2.4흔한 함정: 출력하면서 고치기

메서드를 쓰다 보면 3단계의 E0502 를 자주 만납니다. 아래는 책을 빌려주는 lend(&mut self) 를 만들고, 결과를 println! 안에서 바로 부른 코드입니다.

src/bin/lend_print.rs
struct Book {
    title: String,
    on_shelf: bool,
}

impl Book {
    // 서가에 있으면 빌려주고 true, 이미 나갔으면 false
    fn lend(&mut self) -> bool {
        if !self.on_shelf {
            return false;
        }
        self.on_shelf = false;
        true
    }
}

fn main() {
    let mut b = Book {
        title: String::from("어린 왕자"),
        on_shelf: true,
    };
    println!("{} 첫 대출: {}", b.title, b.lend());
    println!("{} 두 번째 대출: {}", b.title, b.lend());
}
$ cargo build -q --bin lend_print
error[E0502]: cannot borrow `b` as mutable because it is also borrowed as immutable
  --> src/bin/lend_print.rs:22:38
   |
22 |     println!("{} 첫 대출: {}", b.title, b.lend());
   |     ------------------------------------^^^^^^^^-
   |     |                          |        |
   |     |                          |        mutable borrow occurs here
   |     |                          immutable borrow occurs here
   |     immutable borrow later used here

error[E0502]: cannot borrow `b` as mutable because it is also borrowed as immutable
  --> src/bin/lend_print.rs:23:41
   |
23 |     println!("{} 두 번째 대출: {}", b.title, b.lend());
   |     -----------------------------------------^^^^^^^^-
   |     |                               |        |
   |     |                               |        mutable borrow occurs here
   |     |                               immutable borrow occurs here
   |     immutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `errs` (bin "lend_print") due to 2 previous errors

println! 은 인수들을 먼저 모두 빌려 둔 다음 한꺼번에 출력합니다. 그래서 b.title 을 불변으로 빌린 채로 같은 줄의 b.lend() 가 b 를 가변으로 빌리려 하니 규칙 위반입니다. 밑줄 세 개가 각각 불변 빌림, 가변 빌림, 불변 빌림이 아직 쓰이는 곳(매크로 전체)을 가리킵니다. 고치는 방법은 가변 빌림을 먼저 끝내는 것입니다.

src/bin/try_lend.rs
fn main() {
    let mut b = Book {
        title: String::from("어린 왕자"),
        on_shelf: true,
    };
    let first = b.lend();
    println!("{} 첫 대출: {}", b.title, first);
    let second = b.lend();
    println!("{} 두 번째 대출: {}", b.title, second);
}
$ cargo run -q --bin try_lend
어린 왕자 첫 대출: true
어린 왕자 두 번째 대출: false
핵심 정리
  • #[derive(Debug)] 를 붙이면 {:?}(한 줄)·{:#?}(여러 줄)로 출력할 수 있다. 없으면 E0277.
  • 메서드의 첫 매개변수: 읽기 &self, 고치기 &mut self, 소비 self. Self 는 impl 대상 타입.
  • self 가 없는 연관 함수는 타입::함수() 로 부르며, new 는 관례일 뿐 예약어가 아니다.
  • 값.메서드() 는 타입::메서드(&값) 등과 같고, &·&mut 은 자동으로 붙는다.
참고 The Rust Programming Language 5.2~5.3절 · The Rust Reference "Associated Items", "Method call expressions" · std::fmt 문서(Debug, {:#?})
3단원

열거형과 Option

학습 목표
  • 열거형(enum)을 정의하고 변형(variant)을 타입::변형 으로 만들 수 있다.
  • 변형마다 다른 데이터를 담는 열거형을 설계할 수 있다.
  • Option<T> 로 "값이 없을 수도 있음"을 나타내고, Rust 에 null 이 없는 이유를 설명할 수 있다.

3.1가능한 경우를 나열하는 타입

구조체가 "이것과 저것을 함께 가진" 값이라면, 열거형(enum) 은 "이것 또는 저것 중 하나인" 값입니다. 신호등은 빨강, 노랑, 초록 중 정확히 하나의 상태에 있습니다. 이 가능한 경우 하나하나를 변형(variant) 이라고 부릅니다.

src/bin/signal.rs
// 신호등이 가질 수 있는 상태는 딱 셋
#[derive(Debug)]
enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    let now = Light::Red;
    let next = Light::Green;
    let blink = Light::Yellow;
    println!("지금 {:?}, 다음 {:?}, 깜빡임 {:?}", now, next, blink);
    println!("크기: {}바이트", std::mem::size_of::<Light>());
}
$ cargo run -q --bin signal
지금 Red, 다음 Green, 깜빡임 Yellow
크기: 1바이트

변형은 Light::Red 처럼 열거형 이름 아래에 들어 있습니다. Light 타입의 변수에는 이 세 값 말고는 넣을 방법이 없습니다. 세 경우를 구별하기만 하면 되므로 크기도 1바이트입니다. 문자열이나 정수로 상태를 나타내면 오타가 그대로 통과하지만, 열거형은 컴파일러가 가능한 값을 알고 지켜 줍니다.

C와 비교

C의 enum 은 이름 붙은 정수 상수에 가깝습니다. 아래 C 코드는 목록에 없는 값 7을 넣었는데도 -Wall 경고 하나 없이 컴파일되고, switch 는 아무 경우에도 걸리지 않습니다.

c/light.c
#include <stdio.h>

enum light { RED, YELLOW, GREEN };

int main(void) {
    enum light now = 7; /* 없는 값인데도 받아 준다 */
    switch (now) {
    case RED:    puts("빨강"); break;
    case YELLOW: puts("노랑"); break;
    case GREEN:  puts("초록"); break;
    }
    printf("now = %d\n", now);
    return 0;
}
$ gcc -Wall -o light light.c && ./light
now = 7

Rust 에서 같은 일을 하면 컴파일 오류입니다. 열거형은 정수가 아니라 그 자체로 독립된 타입이기 때문입니다.

src/bin/enum_int.rs
#[derive(Debug)]
enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    let now: Light = 7;
    println!("{:?}", now);
}
$ cargo build -q --bin enum_int
error[E0308]: mismatched types
 --> src/bin/enum_int.rs:9:22
  |
9 |     let now: Light = 7;
  |              -----   ^ expected `Light`, found integer
  |              |
  |              expected due to this

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

3.2데이터를 담은 변형

Rust 열거형의 진짜 힘은 변형마다 서로 다른 데이터를 담을 수 있다는 데 있습니다. 가계부의 결제 수단을 생각해 봅시다. 현금은 덧붙일 정보가 없고, 카드는 카드사와 할부 개월 수가, 계좌이체는 은행 이름이 필요합니다.

src/bin/payment.rs
// 가계부의 결제 수단: 변형마다 담는 데이터가 다르다
#[derive(Debug)]
// Cash: 데이터 없음, Card: 이름 붙은 필드, Transfer: 튜플처럼
enum Payment {
    Cash,
    Card { company: String, months: u8 },
    Transfer(String),
}

#[derive(Debug)]
struct Expense {
    item: String,
    amount: u32,
    paid_by: Payment,
}

fn main() {
    let lunch = Expense {
        item: String::from("점심"),
        amount: 9_000,
        paid_by: Payment::Cash,
    };
    let laptop = Expense {
        item: String::from("노트북"),
        amount: 1_200_000,
        paid_by: Payment::Card {
            company: String::from("하나"),
            months: 6,
        },
    };
    let rent = Expense {
        item: String::from("월세"),
        amount: 500_000,
        paid_by: Payment::Transfer(String::from("국민")),
    };
    println!("{:?}", lunch);
    println!("{:?}", laptop);
    println!("{:#?}", rent.paid_by);
    println!("{} {} {}", lunch.item, laptop.amount, rent.item);
}
$ cargo run -q --bin payment
warning: fields `company` and `months` are never read
 --> src/bin/payment.rs:6:12
  |
6 |     Card { company: String, months: u8 },
  |     ----   ^^^^^^^          ^^^^^^
  |     |
  |     fields in this variant
  |
  = note: `Payment` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: field `0` is never read
 --> src/bin/payment.rs:7:14
  |
7 |     Transfer(String),
  |     -------- ^^^^^^
  |     |
  |     field in this variant
  |
  = note: `Payment` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
  |
7 -     Transfer(String),
7 +     Transfer(()),
  |

Expense { item: "점심", amount: 9000, paid_by: Cash }
Expense { item: "노트북", amount: 1200000, paid_by: Card { company: "하나", months: 6 } }
Transfer(
    "국민",
)
점심 1200000 월세

변형은 세 가지 모양 중 하나로 씁니다. 데이터 없는 Cash, 구조체처럼 이름 붙은 필드를 가진 Card { … }, 튜플 구조체처럼 번호 필드를 가진 Transfer(String) 입니다. 모두 같은 Payment 타입이므로 Expense 의 paid_by 필드 하나에 어느 것이든 담을 수 있습니다. 구조체만으로 하려면 "이 필드는 카드일 때만 의미 있음" 같은 약속을 사람이 기억해야 합니다.

출력 위의 경고 두 개(warning: … never read)는 실수가 아니라 사실 그대로입니다. 카드사, 할부 개월, 은행 이름을 저장만 하고 읽는 코드가 아직 없다는 뜻입니다. note 에 적혀 있듯 Debug 출력은 "읽기"로 세지 않습니다. 경고는 컴파일을 막지 않으며, 4단원에서 match 로 이 값들을 꺼내 쓰면 사라집니다.

3.3Option<T>: 값이 있거나 없거나

표준 라이브러리에는 아주 자주 쓰는 열거형이 미리 정의되어 있습니다. "값이 있을 수도, 없을 수도 있음"을 나타내는 Option<T> 입니다. 정의는 개념적으로 다음과 같습니다.

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

<T> 는 "어떤 타입이든 들어갈 자리"라는 뜻입니다(이런 제네릭(generic) 을 직접 만드는 법은 7단계에서 배웁니다). Option<u32> 은 u32 하나를 담은 Some 이거나 None 입니다. 워낙 자주 써서 Option, Some, None 은 Option:: 을 붙이지 않고 바로 쓸 수 있습니다.

src/bin/option.rs
// 학번으로 이름을 찾는다. 없을 수도 있으니 Option 으로 돌려준다
fn find_name(id: u32) -> Option<&'static str> {
    if id == 101 {
        Some("이도윤")
    } else if id == 102 {
        Some("최서연")
    } else {
        None
    }
}

fn main() {
    let a = find_name(101);
    let b = find_name(999);
    println!("{:?} {:?}", a, b);

    let score: Option<u32> = Some(87);
    let nothing: Option<u32> = None;
    println!("{:?} {:?}", score, nothing);
    println!("{}", score.is_some());
    println!("{}", nothing.is_none());
}
$ cargo run -q --bin option
Some("이도윤") None
Some(87) None
true
true

&'static str 는 문자열 리터럴의 타입을 적을 때 쓰는 모양입니다. 'static 은 "프로그램이 끝날 때까지 유효함"을 뜻하는 수명 표시로, 8단계에서 배웁니다. is_some(), is_none() 은 Option 에 딸린 메서드입니다.

None 만 적으면 컴파일러는 "무엇이 없는지"를 알 수 없습니다. 이럴 때는 타입을 적어 줘야 합니다.

src/bin/none_type.rs
fn main() {
    let x = None;
    println!("{:?}", x);
}
$ cargo build -q --bin none_type
error[E0282]: type annotations needed for `Option<_>`
 --> src/bin/none_type.rs:2:9
  |
2 |     let x = None;
  |         ^   ---- type must be known at this point
  |
help: consider giving `x` an explicit type, where the type for type parameter `T` is specified
  |
2 |     let x: Option<T> = None;
  |          +++++++++++

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

3.4null 이 없는 이유

많은 언어에는 "아무것도 가리키지 않음"을 뜻하는 null 이 있고, 거의 모든 참조 변수가 언제든 null 일 수 있습니다. 문제는 그 사실이 타입에 드러나지 않는다는 점입니다. 검사를 빼먹은 한 곳에서 프로그램이 실행 중에 죽습니다. null 참조를 처음 도입한 토니 호어(Tony Hoare)는 2009년 강연에서 이것을 "10억 달러짜리 실수"라고 불렀습니다.

Rust 에는 이런 null 이 없습니다. "없을 수도 있음"이 필요하면 타입을 Option<T> 로 바꿔야 하고, 그 순간 T 와는 다른 타입이 됩니다. 그래서 확인하지 않고 그냥 쓰려고 하면 컴파일러가 막습니다.

src/bin/option_add.rs
fn main() {
    let bonus: Option<u32> = Some(10);
    let score: u32 = 80;
    let total = score + bonus;
    println!("{}", total);
}
$ cargo build -q --bin option_add
error[E0277]: cannot add `Option<u32>` to `u32`
 --> src/bin/option_add.rs:4:23
  |
4 |     let total = score + bonus;
  |                       ^ no implementation for `u32 + Option<u32>`
  |
  = help: the trait `Add<Option<u32>>` is not implemented for `u32`
help: the following other types implement trait `Add<Rhs>`
 --> /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/ops/arith.rs:98:8
  |
  = note: `u32` implements `Add`
 ::: /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/ops/arith.rs:113:0
  |
  = note: in this macro invocation
 --> /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/internal_macros.rs:22:8
  |
  = note: `&u32` implements `Add<u32>`
 ::: /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/internal_macros.rs:33:8
  |
  = note: `u32` implements `Add<&u32>`
 ::: /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/internal_macros.rs:44:8
  |
  = note: `&u32` implements `Add`
  = note: this error originates in the macro `add_impl` (in Nightly builds, run with -Z macro-backtrace for more info)

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

메시지가 길지만 첫 두 줄이 전부입니다. cannot add `Option<u32>` to `u32`, 즉 "있을지 없을지 모르는 값"을 숫자에 더할 수는 없다는 것입니다. 그 아래는 참고 목록입니다. 반대로, 타입이 그냥 u32 라면 그 값은 반드시 있다고 믿어도 됩니다. "없음"을 다루는 코드는 Option 이 있는 곳에만 쓰면 되고, 그 방법이 바로 다음 단원의 match 입니다.

더 알아보기
Option 은 공짜일 때가 있다

참조는 절대 주소 0을 가리키지 않으므로, 컴파일러는 Option<&T> 의 None 을 "주소 0"으로 나타내 꼬리표 칸을 따로 두지 않습니다. 표준 라이브러리 문서는 Option<&T> 가 &T 와 크기가 같음을 보장합니다. 반면 u32 는 모든 비트 조합이 정상 값이라 꼬리표 칸이 따로 필요합니다. 이 서버(64비트)에서 잰 결과입니다.

src/bin/niche.rs
fn main() {
    use std::mem::size_of;
    println!("&u32         : {}바이트", size_of::<&u32>());
    println!("Option<&u32> : {}바이트", size_of::<Option<&u32>>());
    println!("u32          : {}바이트", size_of::<u32>());
    println!("Option<u32>  : {}바이트", size_of::<Option<u32>>());
}
$ cargo run -q --bin niche
&u32         : 8바이트
Option<&u32> : 8바이트
u32          : 4바이트
Option<u32>  : 8바이트

안전한 Option<&T> 가 C의 "널일 수 있는 포인터"와 크기가 같은 셈입니다.

핵심 정리
  • enum 은 "여러 경우 중 하나"인 타입이고, 각 경우가 변형이다. 타입::변형 으로 만든다.
  • 변형은 데이터 없음, 이름 붙은 필드, 번호 필드 중 하나의 모양을 가질 수 있고, 변형마다 달라도 된다.
  • Option<T> 는 Some(T) 또는 None. Option<T> 와 T 는 다른 타입이라 확인 없이 섞어 쓸 수 없다.
  • Rust 에는 null 이 없다. 없을 수 있다는 사실이 타입에 드러난다.
참고 The Rust Programming Language 6.1절 · std::option 문서(Representation 절) · The Rust Reference "Enumerations"
4단원

match: 모든 경우를 빠짐없이

학습 목표
  • match 표현식으로 열거형과 정수 값을 경우에 따라 나눠 처리할 수 있다.
  • 빠짐없음 검사(E0004)가 무엇을 막아 주는지 설명할 수 있다.
  • _, 변수 패턴, |, 범위, 가드를 쓰고, 패턴으로 변형 안의 값을 꺼낼 수 있다.

4.1match 의 기본과 빠짐없음 검사

match 값 { 패턴 => 식, … } 은 값을 위에서부터 차례로 각 갈래(arm) 의 패턴(pattern) 과 맞춰 보고, 처음으로 맞는 갈래 하나의 식만 실행합니다. match 는 if 처럼 표현식이라 값을 돌려주며, 그래서 모든 갈래의 식은 타입이 같아야 합니다.

값 light
→
Red 인가?맞으면 40
→
Yellow 인가?맞으면 3
→
Green 인가?맞으면 0
src/bin/light_match.rs
#[derive(Debug)]
enum Light {
    Red,
    Yellow,
    Green,
}

// match 는 값을 돌려주는 표현식이다
fn wait_seconds(light: Light) -> u32 {
    match light {
        Light::Red => 40,
        Light::Yellow => 3,
        Light::Green => 0,
    }
}

impl Light {
    fn next(&self) -> Light {
        match self {
            Light::Red => Light::Green,
            Light::Green => Light::Yellow,
            Light::Yellow => Light::Red,
        }
    }
}

fn main() {
    let now = Light::Red;
    println!("{:?} 다음은 {:?}", now, now.next());
    println!("기다릴 시간: {}초", wait_seconds(now));
    println!("기다릴 시간: {}초", wait_seconds(Light::Yellow));
    println!("기다릴 시간: {}초", wait_seconds(Light::Green));
}
$ cargo run -q --bin light_match
Red 다음은 Green
기다릴 시간: 40초
기다릴 시간: 3초
기다릴 시간: 0초

impl Light 처럼 열거형에도 메서드를 붙일 수 있습니다. next(&self) 안의 self 는 &Light 인데 패턴은 Light::Red 로 적었습니다. 참조를 match 할 때 컴파일러가 알아서 참조를 따라가 맞춰 보기 때문에 &Light::Red 라고 쓰지 않아도 됩니다.

match 의 가장 중요한 성질은 빠짐없음(exhaustiveness) 입니다. 가능한 값 중 하나라도 어느 갈래에도 맞지 않으면 컴파일되지 않습니다. 노란불 갈래를 지워 보면 이렇습니다.

src/bin/missing_arm.rs
enum Light {
    Red,
    Yellow,
    Green,
}

fn wait_seconds(light: Light) -> u32 {
    match light {
        Light::Red => 40,
        Light::Green => 0,
    }
}

fn main() {
    println!("{}", wait_seconds(Light::Yellow));
}
$ cargo build -q --bin missing_arm
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
  --> src/bin/missing_arm.rs:8:11
   |
 8 |     match light {
   |           ^^^^^ pattern `Light::Yellow` not covered
   |
note: `Light` defined here
  --> src/bin/missing_arm.rs:1:6
   |
 1 | enum Light {
   |      ^^^^^
 2 |     Red,
 3 |     Yellow,
   |     ------ not covered
   = note: the matched value is of type `Light`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
10 ~         Light::Green => 0,
11 ~         Light::Yellow => todo!(),
   |

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

E0004 는 "덮지 않은 패턴이 있음"입니다. pattern `Light::Yellow` not covered 가 빠진 경우를 정확히 이름으로 알려 주고, note 는 열거형 정의에서 그 변형의 자리를, help 는 추가할 갈래를 보여 줍니다(todo!() 는 "아직 안 만듦"이라는 뜻으로, 실행되면 패닉하는 매크로입니다). Option 에서 None 을 빠뜨려도 똑같이 막힙니다.

src/bin/missing_none.rs
fn main() {
    let found: Option<&str> = None;
    match found {
        Some(name) => println!("{}", name),
    }
}
$ cargo build -q --bin missing_none
error[E0004]: non-exhaustive patterns: `None` not covered
 --> src/bin/missing_none.rs:3:11
  |
3 |     match found {
  |           ^^^^^ pattern `None` not covered
  |
note: `Option<&str>` defined here
 --> /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/option.rs:598:0
 ::: /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/option.rs:602:4
  |
  = note: not covered
  = note: the matched value is of type `Option<&str>`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
4 ~         Some(name) => println!("{}", name),
5 ~         None => todo!(),
  |

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

note 의 /rustc/…/option.rs 는 표준 라이브러리 속 Option 정의의 위치입니다.

C와 비교

C의 switch 에서 경우를 빠뜨리면 -Wall 이 경고는 해 주지만 컴파일은 그대로 되고, 프로그램은 빠진 경우를 만나면 조용히 엉뚱한 길(여기서는 -1)로 갑니다.

c/missing.c
#include <stdio.h>

enum light { RED, YELLOW, GREEN };

int wait_seconds(enum light l) {
    switch (l) {
    case RED:   return 40;
    case GREEN: return 0;
    }
    return -1;
}

int main(void) {
    printf("%d\n", wait_seconds(YELLOW));
    return 0;
}
$ gcc -Wall -o missing missing.c && ./missing
missing.c: In function ‘wait_seconds’:
missing.c:6:5: warning: enumeration value ‘YELLOW’ not handled in switch [-Wswitch]
    6 |     switch (l) {
      |     ^~~~~~
-1

Rust 는 같은 실수를 경고가 아니라 오류로 다룹니다. 나중에 열거형에 변형을 하나 추가하면, 그 열거형을 _ 없이 match 하는 모든 곳이 컴파일 오류로 "여기도 고쳐라"라고 알려 줍니다. 또 C의 switch 와 달리 갈래가 아래로 흘러내리지(fall through) 않으므로 break 가 필요 없습니다.

4.2패턴의 여러 모양: _, 변수, |, 범위, 가드

정수처럼 가능한 값이 아주 많은 타입은 모든 값을 나열할 수 없으니, 나머지를 한꺼번에 받는 갈래가 필요합니다.

src/bin/grade.rs
fn grade(score: u32) -> char {
    match score {
        90..=100 => 'A',
        80..=89 => 'B',
        70..=79 => 'C',
        0..=69 => 'F',
        _ => '?', // 100 보다 큰 값
    }
}

fn day_kind(day: u8) -> &'static str {
    match day {
        6 | 7 => "주말",
        1..=5 => "평일",
        other => {
            println!("  ({}번은 요일 번호가 아닙니다)", other);
            "없음"
        }
    }
}

fn main() {
    for s in [95, 83, 70, 12, 130] {
        println!("{}점 → {}", s, grade(s));
    }
    println!("{}", day_kind(3));
    println!("{}", day_kind(7));
    println!("{}", day_kind(9));
}
$ cargo run -q --bin grade
95점 → A
83점 → B
70점 → C
12점 → F
130점 → ?
평일
주말
  (9번은 요일 번호가 아닙니다)
없음
  • 90..=100 은 범위 패턴으로 90 이상 100 이하에 맞습니다.
  • 6 | 7 은 "6 또는 7"입니다.
  • _ 는 무엇에든 맞고 값을 버립니다. 0부터 100까지는 앞 갈래들이 덮었지만 u32 에는 101 이상도 있으므로 _ 가 없으면 E0004 입니다.
  • other 처럼 변수 이름을 패턴으로 쓰면 무엇에든 맞으면서 그 값을 그 이름에 묶어(바인딩) 갈래 안에서 쓸 수 있습니다.

갈래는 위에서부터 검사하므로 순서가 중요합니다. _ 나 변수 패턴처럼 모든 것에 맞는 갈래는 맨 끝에 둡니다. 앞에 두면 뒤 갈래는 영영 실행되지 않고, 컴파일러가 unreachable pattern 경고를 냅니다. 경고라서 실행은 되지만 결과는 의도와 다릅니다(80cm 인데 "작음"이 아니라 "보통").

src/bin/unreachable.rs
fn size_name(cm: u32) -> &'static str {
    match cm {
        _ => "보통",
        0..=90 => "작음", // 영영 닿지 않는 갈래
    }
}

fn main() {
    println!("{}", size_name(80));
}
$ cargo run -q --bin unreachable
warning: unreachable pattern
 --> src/bin/unreachable.rs:4:9
  |
3 |         _ => "보통",
  |         - matches any value
4 |         0..=90 => "작음", // 영영 닿지 않는 갈래
  |         ^^^^^^ no value can reach this
  |
  = note: `#[warn(unreachable_patterns)]` (part of `#[warn(unused)]`) on by default

보통

패턴만으로 표현하기 어려운 조건은 패턴 뒤에 if 조건 을 붙이는 매치 가드(match guard) 로 씁니다. 패턴이 맞고 그리고 조건이 참이어야 그 갈래가 선택됩니다.

src/bin/guard.rs
fn shipping(weight_kg: u32, island: bool) -> u32 {
    match weight_kg {
        0 => 0,
        w if island => 7_000 + w * 500, // 가드: 조건이 참일 때만
        1..=5 => 3_000,
        _ => 5_000,
    }
}

fn main() {
    println!("{}", shipping(0, false));
    println!("{}", shipping(3, false));
    println!("{}", shipping(3, true));
    println!("{}", shipping(12, false));
}
$ cargo run -q --bin guard
0
3000
8500
5000

shipping(3, true) 는 두 번째 갈래 w if island 에서 w 가 3으로 묶이고 island 가 참이라 7,000 + 3×500 = 8,500 이 됩니다. 가드가 거짓이면 그 갈래는 건너뛰고 다음 갈래로 내려갑니다. 단, 빠짐없음 검사는 가드 조건 속까지 따지지 않습니다. 아래 두 가드는 사람 눈에는 모든 정수를 덮지만, 컴파일러는 가드 붙은 갈래를 빼고 셉니다. note 의 match arms with guards don't count towards exhaustivity 가 바로 그 말입니다. 두 번째 갈래를 가드 없는 _ 로 바꾸면 해결됩니다.

src/bin/guard_only.rs
fn sign(n: i32) -> &'static str {
    match n {
        x if x < 0 => "음수",
        x if x >= 0 => "0 또는 양수",
    }
}

fn main() {
    println!("{}", sign(-4));
}
$ cargo build -q --bin guard_only
error[E0004]: non-exhaustive patterns: `i32::MIN..=i32::MAX` not covered
 --> src/bin/guard_only.rs:2:11
  |
2 |     match n {
  |           ^ pattern `i32::MIN..=i32::MAX` not covered
  |
  = note: the matched value is of type `i32`
  = note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
4 ~         x if x >= 0 => "0 또는 양수",
5 ~         i32::MIN..=i32::MAX => todo!(),
  |

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

4.3변형 안의 데이터 꺼내기

패턴은 값을 분해할 수도 있습니다. 변형의 필드 자리에 이름을 적으면 그 안의 값이 그 이름에 묶입니다. 3단원에서 경고를 냈던 결제 수단의 데이터를 이제 꺼내 써 봅니다.

src/bin/pay_match.rs
enum Payment {
    Cash,
    Card { company: String, months: u8 },
    Transfer(String),
}

// 변형 안의 데이터를 패턴에서 꺼내 이름(바인딩)을 붙인다
fn describe(p: &Payment) {
    match p {
        Payment::Cash => println!("현금"),
        Payment::Card { company, months: 0 } => {
            println!("{}카드 일시불", company)
        }
        Payment::Card { company, months } => {
            println!("{}카드 {}개월 할부", company, months)
        }
        Payment::Transfer(bank) => println!("{} 계좌이체", bank),
    }
}

fn main() {
    let list = [
        Payment::Cash,
        Payment::Card { company: String::from("신한"), months: 0 },
        Payment::Card { company: String::from("하나"), months: 6 },
        Payment::Transfer(String::from("국민")),
    ];
    for p in &list {
        describe(p);
    }
}
$ cargo run -q --bin pay_match
현금
신한카드 일시불
하나카드 6개월 할부
국민 계좌이체
  • Payment::Transfer(bank) 는 튜플 변형 속 String 을 bank 로 묶습니다.
  • Payment::Card { company, months } 는 필드 이름과 같은 변수 이름으로 묶는 단축 모양입니다. months: m 처럼 다른 이름을 붙일 수도 있습니다.
  • Payment::Card { company, months: 0 } 처럼 필드 자리에 값을 적으면 "할부 개월이 0인 카드"에만 맞습니다. 그래서 이 갈래를 일반 카드 갈래보다 위에 둡니다.

describe 는 &Payment 를 받았으므로 소유권을 가져오지 않습니다. 이때 company, bank 는 String 이 아니라 &String 으로 묶입니다. 빌린 값을 분해하면 그 안의 값도 빌려서 볼 뿐, 꺼내 가지 않는다는 뜻입니다. for p in &list 는 원소를 하나씩 빌려서 도는 반복입니다(6단계).

4.4Option 을 match 로 다루기

3단원의 Option 도 열거형이므로 같은 방법으로 다룹니다. Some(name) 갈래 안에서 name 은 꺼낸 값 그 자체이고, None 갈래를 빠뜨리면 컴파일되지 않으니 "없는 경우"를 잊을 수 없습니다.

src/bin/option_match.rs
fn find_name(id: u32) -> Option<&'static str> {
    match id {
        101 => Some("이도윤"),
        102 => Some("최서연"),
        _ => None,
    }
}

// 있으면 점수에 10을 더하고, 없으면 그대로 없음
fn add_bonus(score: Option<u32>) -> Option<u32> {
    match score {
        Some(s) => Some(s + 10),
        None => None,
    }
}

fn main() {
    for id in [101, 102, 103] {
        match find_name(id) {
            Some(name) => println!("{}번: {}", id, name),
            None => println!("{}번: 없는 학번", id),
        }
    }
    println!("{:?}", add_bonus(Some(75)));
    println!("{:?}", add_bonus(None));
}
$ cargo run -q --bin option_match
101번: 이도윤
102번: 최서연
103번: 없는 학번
Some(85)
None

add_bonus 는 "있으면 바꾸고, 없으면 없음 그대로"라는, Option 을 다룰 때 아주 흔한 모양입니다.

핵심 정리
  • match 는 위에서부터 처음 맞는 갈래 하나만 실행하는 표현식이다. 갈래들의 값 타입은 같아야 한다.
  • 모든 경우를 덮지 않으면 E0004. 남는 경우는 _(버림) 또는 변수 패턴(묶음)으로 받는다.
  • 패턴: 리터럴, a | b, 1..=5, 변형(x), 변형 { 필드, … }. 가드 if 조건 으로 조건을 더한다.
  • 참조를 match 하면 묶인 값도 참조가 되어, 소유권을 가져오지 않는다.
참고 The Rust Programming Language 6.2절, 19장(패턴) · The Rust Reference "Match expressions", "Patterns" · rustc 오류 설명 E0004
5단원

짧게 쓰는 패턴: if let, let else, while let, matches!

학습 목표
  • 한 경우만 관심 있을 때 if let 으로 match 를 줄여 쓸 수 있다.
  • let else 로 "없으면 일찍 빠져나가기"를 쓰고, else 블록이 빠져나가야 하는 이유를 설명할 수 있다.
  • while let 과 matches! 의 쓰임새를 안다.

5.1if let

match 는 모든 경우를 다루게 하지만, 정말 한 경우에만 관심이 있을 때는 None => {} 같은 빈 갈래를 적는 것이 번거롭습니다. if let 패턴 = 값 { … } 은 "값이 패턴에 맞으면 블록을 실행하고, 아니면 건너뛴다"는 뜻입니다. else 를 붙일 수도 있습니다.

src/bin/if_let.rs
fn find_name(id: u32) -> Option<&'static str> {
    match id {
        101 => Some("이도윤"),
        _ => None,
    }
}

fn main() {
    // 한 경우만 관심 있을 때
    if let Some(name) = find_name(101) {
        println!("찾았다: {}", name);
    }

    // else 를 붙일 수도 있다
    if let Some(name) = find_name(555) {
        println!("찾았다: {}", name);
    } else {
        println!("555번은 없습니다");
    }
}
$ cargo run -q --bin if_let
찾았다: 이도윤
555번은 없습니다

패턴이 왼쪽, 검사할 값이 오른쪽이며 = 는 대입이 아니라 "맞춰 본다"는 표시입니다. if let 은 짧은 대신 빠짐없음 검사를 포기하므로, 경우마다 처리가 다르면 match 가 더 안전합니다.

5.2let else: 없으면 일찍 빠져나가기

함수 앞부분에서 "값이 없으면 여기서 그만"을 처리하고, 그 뒤로는 꺼낸 값을 편하게 쓰고 싶을 때가 많습니다. if let 을 쓰면 나머지 코드가 전부 블록 안으로 들여 써집니다. let 패턴 = 값 else { … }; 은 패턴이 맞으면 묶인 변수를 바깥 스코프에 만들어 주고, 맞지 않으면 else 블록을 실행합니다.

src/bin/let_else.rs
fn price_of(menu: &str) -> Option<u32> {
    match menu {
        "아메리카노" => Some(2_500),
        "라테" => Some(3_200),
        _ => None,
    }
}

fn order(menu: &str, cups: u32) {
    // 값이 없으면 else 블록에서 함수를 빠져나간다
    let Some(price) = price_of(menu) else {
        println!("{}: 메뉴에 없습니다", menu);
        return;
    };
    // 여기부터 price 는 그냥 u32
    println!("{} {}잔: {}원", menu, cups, price * cups);
}

fn main() {
    order("라테", 2);
    order("녹차", 1);
    order("아메리카노", 3);
}
$ cargo run -q --bin let_else
라테 2잔: 6400원
녹차: 메뉴에 없습니다
아메리카노 3잔: 7500원

조건이 하나 있습니다. else 블록은 반드시 바깥으로 빠져나가야(diverge) 합니다. return, 반복문 안의 break·continue, 또는 panic! 같은 것으로 끝나야 합니다. 그렇지 않으면 블록이 끝난 뒤 price 에 넣을 값이 없기 때문입니다.

src/bin/let_else_bad.rs
fn main() {
    let input: Option<u32> = None;
    let Some(n) = input else {
        println!("값이 없음");
    };
    println!("{}", n);
}
$ cargo build -q --bin let_else_bad
error[E0308]: `else` clause of `let...else` does not diverge
 --> src/bin/let_else_bad.rs:3:30
  |
3 |       let Some(n) = input else {
  |  ______________________________^
4 | |         println!("값이 없음");
5 | |     };
  | |_____^ expected `!`, found `()`
  |
  = note:   expected type `!`
          found unit type `()`
  = help: try adding a diverging expression, such as `return` or `panic!(..)`
  = help: ...or use `match` instead of `let...else`

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

expected `!`, found `()` 의 ! 는 "절대 정상적으로 끝나지 않음"을 뜻하는 타입입니다. 블록이 println! 만 하고 끝나서 () 가 되었으니 맞지 않는다는 말이고, help 가 return 을 넣거나 match 를 쓰라고 권합니다. let else 는 Rust 1.65(2022년 11월)에 들어온 문법이라 오래된 자료에는 없습니다.

5.3while let 맛보기

while let 패턴 = 값 { … } 은 값이 패턴에 맞는 동안 반복합니다. "꺼낼 것이 있는 동안 꺼내기"에 딱 맞습니다. 아래 번호표 기계의 take 는 남은 번호표가 있으면 Some(번호), 다 떨어지면 None 을 돌려주는 메서드입니다.

src/bin/while_let.rs
// 번호표 기계: 남은 번호표가 있으면 Some, 다 떨어지면 None
struct Dispenser {
    next: u32,
    last: u32,
}

impl Dispenser {
    fn take(&mut self) -> Option<u32> {
        if self.next > self.last {
            return None;
        }
        let n = self.next;
        self.next += 1;
        Some(n)
    }
}

fn main() {
    let mut d = Dispenser { next: 1, last: 3 };
    // take() 가 Some 을 주는 동안 반복
    while let Some(n) = d.take() {
        println!("{}번 손님", n);
    }
    println!("번호표가 다 떨어졌습니다");
}
$ cargo run -q --bin while_let
1번 손님
2번 손님
3번 손님
번호표가 다 떨어졌습니다

반복마다 d.take() 를 새로 부르고, None 이 나오면 끝납니다. "다음 것을 Option 으로 주는" 이 모양은 9단계 반복자(iterator)의 방식과 같습니다.

5.4matches! 매크로

값이 어떤 패턴에 맞는지 true/false 만 알고 싶을 때는 matches!(값, 패턴) 을 씁니다. match 의 패턴 문법(|, 범위, 가드)을 그대로 쓸 수 있습니다.

src/bin/matches_demo.rs
#[derive(Debug)]
enum Seat {
    Empty,
    Taken(String),
    Broken,
}

fn main() {
    let seats = [
        Seat::Taken(String::from("민지")),
        Seat::Empty,
        Seat::Broken,
        Seat::Empty,
    ];
    let mut free = 0;
    for s in &seats {
        if matches!(s, Seat::Empty) {
            free += 1;
        }
    }
    println!("빈자리 {}개", free);

    // 패턴에 | 와 범위, 가드도 쓸 수 있다
    let c = 'k';
    println!("{}", matches!(c, 'a'..='z' | 'A'..='Z'));
    let n = Some(42);
    println!("{}", matches!(n, Some(x) if x % 2 == 0));
    println!("{:?}", seats[2]);
    if let Seat::Taken(name) = &seats[0] {
        println!("1번 자리: {}", name);
    }
}
$ cargo run -q --bin matches_demo
빈자리 2개
true
true
Broken
1번 자리: 민지

matches!(s, Seat::Empty) 는 다음 match 를 줄여 쓴 것과 같습니다: match s { Seat::Empty => true, _ => false }. == 비교(7단계의 PartialEq)가 없는 열거형에도 쓸 수 있습니다.

경우가 여럿, 모두 처리match
·
한 경우만if let
·
없으면 빠져나가기let else
·
맞는 동안 반복while let
·
맞나 안 맞나matches!
핵심 정리
  • if let 패턴 = 값: 한 경우만 처리. 짧지만 빠짐없음 검사는 없다.
  • let 패턴 = 값 else { 빠져나가기 };: 맞으면 변수가 바깥에 생긴다. else 는 반드시 diverge.
  • while let: 패턴이 맞는 동안 반복. matches!: 맞는지 bool 로.

5.5연습문제

1. 이름과 국어·영어·수학 점수를 가진 Student 구조체를 만들고, 연관 함수 new, 총점 total, 평균 average(f64), 평균 60 이상이면 true 인 passed 메서드를 작성하세요.

풀이 보기

average 는 total 을 다시 써서 중복을 줄였고, as f64 로 바꾼 뒤 나눕니다. new 안에서는 필드 초기화 단축을 썼습니다.

src/bin/ex1_student.rs
struct Student {
    name: String,
    kor: u32,
    eng: u32,
    math: u32,
}

impl Student {
    fn new(name: &str, kor: u32, eng: u32, math: u32) -> Self {
        Student { name: String::from(name), kor, eng, math }
    }

    fn total(&self) -> u32 {
        self.kor + self.eng + self.math
    }

    fn average(&self) -> f64 {
        self.total() as f64 / 3.0
    }

    fn passed(&self) -> bool {
        self.average() >= 60.0
    }
}

fn main() {
    let a = Student::new("한지우", 88, 92, 79);
    let b = Student::new("오민혁", 45, 70, 52);
    for s in [&a, &b] {
        println!("{}: 총점 {}, 평균 {:.1}, 통과 {}",
                 s.name, s.total(), s.average(), s.passed());
    }
}
$ cargo run -q --bin ex1_student
한지우: 총점 259, 평균 86.3, 통과 true
오민혁: 총점 167, 평균 55.7, 통과 false

2. 튜플 구조체 Celsius(f64), Fahrenheit(f64) 에 서로 바꾸는 메서드 to_fahrenheit, to_celsius 를 붙이세요. 원래 값은 바꾼 뒤에도 쓸 수 있어야 합니다.

풀이 보기

원래 값을 남겨야 하므로 self 가 아니라 &self 를 받습니다.

src/bin/ex2_temp.rs
struct Celsius(f64);
struct Fahrenheit(f64);

impl Celsius {
    fn to_fahrenheit(&self) -> Fahrenheit {
        Fahrenheit(self.0 * 9.0 / 5.0 + 32.0)
    }
}

impl Fahrenheit {
    fn to_celsius(&self) -> Celsius {
        Celsius((self.0 - 32.0) * 5.0 / 9.0)
    }
}

fn main() {
    let boil = Celsius(100.0);
    println!("섭씨 100도 = 화씨 {:.1}도", boil.to_fahrenheit().0);
    let body = Fahrenheit(98.6);
    println!("화씨 98.6도 = 섭씨 {:.1}도", body.to_celsius().0);
}
$ cargo run -q --bin ex2_temp
섭씨 100도 = 화씨 212.0도
화씨 98.6도 = 섭씨 37.0도

3. 승객 종류 열거형 Rider(어른, 청소년, 어린이, 경로)와, 종류에 따라 요금을 돌려주는 함수 fare 를 match 로 작성하고 일행의 요금 합계를 구하세요(요금은 마음대로 정해도 됩니다).

풀이 보기

fare 가 &Rider 를 받으므로 배열을 &group 으로 빌려서 돕니다. 변형을 하나 추가하면 fare 가 E0004 로 알려 줍니다.

src/bin/ex3_fare.rs
#[derive(Debug)]
enum Rider {
    Adult,
    Teen,
    Child,
    Senior,
}

// 이 문제에서 정한 요금표 (실제 요금과는 다를 수 있다)
fn fare(r: &Rider) -> u32 {
    match r {
        Rider::Adult => 1_500,
        Rider::Teen => 900,
        Rider::Child => 500,
        Rider::Senior => 0,
    }
}

fn main() {
    let group = [Rider::Adult, Rider::Teen, Rider::Child,
                 Rider::Senior, Rider::Adult];
    let mut sum = 0;
    for r in &group {
        println!("{:?}: {}원", r, fare(r));
        sum += fare(r);
    }
    println!("합계 {}원", sum);
}
$ cargo run -q --bin ex3_fare
Adult: 1500원
Teen: 900원
Child: 500원
Senior: 0원
Adult: 1500원
합계 4400원

4. 0으로 나누면 None 을 돌려주는 divide(a, b) -> Option<i32> 를 만들고, let else 로 결과를 출력하는 report 함수를 작성하세요.

풀이 보기

정수 나눗셈이라 7 / 2 는 3입니다. 0으로 나누면 패닉하는 대신 None 으로 "결과 없음"을 알립니다.

src/bin/ex4_divide.rs
fn divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 {
        None
    } else {
        Some(a / b)
    }
}

fn report(total: i32, people: i32) {
    let Some(each) = divide(total, people) else {
        println!("{}원: 나눌 사람이 없습니다", total);
        return;
    };
    println!("{}원을 {}명이 나누면 {}원씩", total, people, each);
}

fn main() {
    report(36_000, 4);
    report(10_000, 0);
    if let Some(q) = divide(7, 2) {
        println!("7 / 2 = {}", q);
    }
}
$ cargo run -q --bin ex4_divide
36000원을 4명이 나누면 9000원씩
10000원: 나눌 사람이 없습니다
7 / 2 = 3

5. 자판기를 만드세요. 명령 열거형 Command 는 돈 넣기 Insert(금액), 고르기 Select, 반환 Refund 이고, Machine 구조체(들어온 돈, 재고)의 handle(&mut self, cmd) 메서드가 명령을 처리합니다. 값은 1,200원이며 품절과 돈 부족을 알려야 합니다.

풀이 보기

Command::Select 를 가드로 품절·돈 부족·성공 세 갈래로 나눴습니다. 가드 붙은 갈래는 빠짐없음에 세지 않으므로 가드 없는 마지막 Select 갈래가 꼭 필요합니다.

src/bin/ex5_vending.rs
enum Command {
    Insert(u32),
    Select,
    Refund,
}

struct Machine {
    money: u32,
    stock: u32,
}

const PRICE: u32 = 1_200;

impl Machine {
    fn handle(&mut self, cmd: Command) {
        match cmd {
            Command::Insert(won) => {
                self.money += won;
                println!("{}원 넣음 (현재 {}원)", won, self.money);
            }
            Command::Select if self.stock == 0 => {
                println!("품절입니다");
            }
            Command::Select if self.money < PRICE => {
                println!("{}원 모자랍니다", PRICE - self.money);
            }
            Command::Select => {
                self.money -= PRICE;
                self.stock -= 1;
                println!("음료 나옴 (남은 돈 {}원)", self.money);
            }
            Command::Refund => {
                println!("{}원 반환", self.money);
                self.money = 0;
            }
        }
    }
}

fn main() {
    let mut m = Machine { money: 0, stock: 1 };
    let cmds = [
        Command::Insert(1_000),
        Command::Select,
        Command::Insert(500),
        Command::Select,
        Command::Select,
        Command::Refund,
    ];
    for c in cmds {
        m.handle(c);
    }
}
$ cargo run -q --bin ex5_vending
1000원 넣음 (현재 1000원)
200원 모자랍니다
500원 넣음 (현재 1500원)
음료 나옴 (남은 돈 300원)
품절입니다
300원 반환
참고 The Rust Programming Language 6.3절 · The Rust Reference "let statements"(let-else), "Predicate loops" · std::matches 문서 · Rust 1.65.0 릴리스 공지