$ cargo run --stage 8

8단계: 수명과 스마트 포인터 강의 노트

수명 매개변수 'a 를 언제 왜 적는지, 생략 규칙 세 가지와 참조를 담은 구조체, 'static 을 다룬 뒤 Box·Deref·Drop·Rc·RefCell·Weak 로 소유와 빌림의 규칙을 넓혀 봅니다. 모든 오류 메시지는 rustc 1.99.1 의 실제 출력입니다.

기간 29~32주구성 5개 단원
1단원

수명 표시: 참조가 어디서 왔는지 밝히기

학습 목표
  • 참조의 수명(lifetime)이 무엇이고, 빌림 검사기(borrow checker)가 수명을 어떻게 비교하는지 설명할 수 있다.
  • E0106 이 왜 나오는지 알고 함수 시그니처에 'a 를 붙여 고칠 수 있다.
  • E0597 과 E0515 를 읽고, 수명 표시로 고칠 수 있는 오류와 고칠 수 없는 오류를 구별할 수 있다.

1.1참조는 빌려 온 값보다 오래 살 수 없다

참조(reference)가 쓰이는 동안에는 원래 값이 살아 있어야 합니다. 어떤 참조가 유효하게 쓰일 수 있는 코드 구간을 그 참조의 수명(lifetime)이라고 부릅니다. 수명은 실행 중에 재는 시간이 아니라, 컴파일러(compiler)가 코드를 보고 판단하는 "어디부터 어디까지"입니다.

빌림 검사기는 참조가 마지막으로 쓰이는 곳까지 원래 값이 살아 있는지 확인합니다. 아래 코드는 안쪽 블록의 tree 를 빌린 결과를 블록 밖에서 씁니다.

src/bin/short_scope.rs
fn first_in_dict<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a <= b { a } else { b }
}

fn main() {
    let fruit = String::from("사과");
    let w;
    {
        let tree = String::from("나무");
        w = first_in_dict(&fruit, &tree);
    } // tree 가 여기서 사라진다
    println!("먼저 나오는 말: {w}");
}
$ cargo run --bin short_scope
   Compiling errors v0.1.0 (…/p8/errors)
error[E0597]: `tree` does not live long enough
  --> src/bin/short_scope.rs:10:35
   |
 9 |         let tree = String::from("나무");
   |             ---- binding `tree` declared here
10 |         w = first_in_dict(&fruit, &tree);
   |                                   ^^^^^ borrowed value does not live long enough
11 |     } // tree 가 여기서 사라진다
   |     - `tree` dropped here while still borrowed
12 |     println!("먼저 나오는 말: {w}");
   |                                - borrow later used here

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

error[E0597] 은 "빌린 값이 충분히 오래 살지 않는다"는 뜻, --> 줄은 문제의 빌림 &tree 의 위치(10번째 줄 35번째 글자)입니다. 아래 표시는 9번째 줄의 tree 가 11번째 줄에서 빌린 채로 사라지는데 12번째 줄에서 그 빌림이 쓰인다는 뜻입니다.

줄 68 910 1112 fruit 이 살아 있는 구간 tree 가 살아 있는 구간 w(빌림)를 쓰는 구간 여기서 tree 정리 → 12줄의 w 는 매달린 참조
그림 1. E0597 의 뜻: 빌림을 쓰는 구간(12줄)이 빌려 온 값 tree 의 수명(9~11줄) 밖으로 나간다.

고치는 방법은 두 가지입니다. tree 를 바깥 블록으로 옮겨 오래 살게 하거나, 결과를 tree 가 살아 있는 블록 안에서 다 쓰는 것입니다.

src/bin/inner_ok.rs
fn first_in_dict<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a <= b { a } else { b }
}

fn main() {
    let fruit = String::from("사과");
    {
        let tree = String::from("나무");
        let w = first_in_dict(&fruit, &tree);
        println!("먼저 나오는 말: {w}"); // tree 가 살아 있을 때 쓴다
    }
}
$ cargo run --bin inner_ok
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/inner_ok`
먼저 나오는 말: 나무

1.2E0106: 돌려주는 참조는 어디서 왔나

함수 안만 보면 빌림 검사기는 수명을 스스로 알아냅니다. 문제는 함수 경계입니다. 컴파일러는 함수를 부르는 쪽을 검사할 때 함수 몸통을 다시 들여다보지 않고 시그니처(이름, 매개변수, 반환 타입)만 봅니다. 그래서 참조를 돌려주는 함수라면 "돌려주는 참조가 어느 매개변수에서 빌린 것인지"가 시그니처에 드러나야 합니다.

src/bin/no_label.rs
// 두 단어 중 사전에서 먼저 나오는 쪽을 돌려준다 (수명 표시 없음)
fn first_in_dict(a: &str, b: &str) -> &str {
    if a <= b { a } else { b }
}

fn main() {
    let w = first_in_dict("사과", "바나나");
    println!("{w}");
}
$ cargo run --bin no_label
   Compiling errors v0.1.0 (…/p8/errors)
error[E0106]: missing lifetime specifier
 --> src/bin/no_label.rs:2:39
  |
2 | fn first_in_dict(a: &str, b: &str) -> &str {
  |                     ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
2 | fn first_in_dict<'a>(a: &'a str, b: &'a str) -> &'a str {
  |                 ++++     ++          ++          ++

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

^ 는 반환 타입의 & 를, 밑줄 ---- 두 개는 두 매개변수를 가리킵니다. 첫 help 는 반환값을 a, b 중 어디서 빌렸는지 시그니처가 말하지 않는다는 뜻, 둘째는 고친 모양을 + 로 보여 줍니다.

1.3수명 매개변수 'a 의 문법과 뜻

수명 매개변수는 작은따옴표로 시작하는 이름입니다. 보통 'a, 'b 처럼 짧게 짓습니다. 제네릭(generic) 타입 매개변수처럼 함수 이름 뒤 꺾쇠 안에 먼저 선언하고(fn f<'a>), 참조 타입의 & 바로 뒤에 붙입니다(&'a str, &'a mut i32).

src/bin/dict.rs
// 두 단어 중 사전에서 먼저 나오는 쪽을 돌려준다
fn first_in_dict<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a <= b { a } else { b }
}

fn main() {
    let fruit = String::from("사과");
    let tree = String::from("나무");
    let w = first_in_dict(&fruit, &tree);
    println!("먼저 나오는 말: {w}");
    println!("{}", first_in_dict("zebra", "apple"));
}
$ cargo run --bin dict
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/dict`
먼저 나오는 말: 나무
apple

이 시그니처는 "a 와 b 가 모두 적어도 'a 동안 유효하면, 돌려주는 참조도 'a 동안 유효하다"는 약속입니다. 부르는 쪽에서 컴파일러는 'a 를 두 인자의 수명이 겹치는 구간(짧은 쪽)으로 정합니다. 1.1에서 'a 가 tree 의 수명으로 정해져 오류가 난 까닭입니다.

중요한 점이 하나 있습니다. 수명 표시는 값이 사는 기간을 바꾸지 않습니다. 'a 를 붙인다고 tree 가 더 오래 사는 것이 아닙니다. 수명 표시는 여러 참조 사이의 관계를 컴파일러에게 알려 주는 설명일 뿐이고, 컴파일러는 그 설명과 실제 코드가 맞는지 검사합니다. 함수 몸통에서 약속을 어기면(예: 'a 와 관계없는 참조를 돌려주면) 함수 쪽에서 오류가 납니다.

왜 이렇게 만들었을까

호출할 때마다 몸통까지 분석한다면 함수 안을 조금 고쳤을 뿐인데 멀리 있는 호출 코드가 깨질 수 있습니다. 시그니처를 약속으로 삼으면 함수 쪽은 약속만 지키고, 부르는 쪽은 시그니처만 보고 안전하게 쓸 수 있습니다.

1.4관계있는 참조만 묶고, 새 값은 소유로 돌려준다

결과가 한 매개변수에서만 나온다면 그 매개변수와 반환 타입만 묶습니다. 아래 before 의 결과는 언제나 text 의 일부이므로, 수명을 적지 않은 sep 에 넘긴 comma 는 먼저 사라져도 됩니다.

src/bin/before.rs
// 돌려주는 값은 text 에서만 나온다. sep 는 결과와 상관없다.
fn before<'a>(text: &'a str, sep: &str) -> &'a str {
    match text.find(sep) {
        Some(i) => &text[..i],
        None => text,
    }
}

fn main() {
    let line = String::from("김민지,92,서울");
    let name;
    {
        let comma = String::from(",");
        name = before(&line, &comma);
    } // comma 는 사라져도 된다
    println!("이름: {name}");
}
$ cargo run --bin before
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/before`
이름: 김민지

반대로 수명 표시로 고칠 수 없는 경우도 있습니다. 함수 안에서 새로 만든 값의 참조를 돌려주는 경우입니다.

src/bin/local_ref.rs
fn greeting<'a>(name: &str) -> &'a str {
    let s = format!("안녕하세요, {name}님");
    &s
}

fn main() {
    println!("{}", greeting("민지"));
}
$ cargo run --bin local_ref
   Compiling errors v0.1.0 (…/p8/errors)
error[E0515]: cannot return reference to local variable `s`
 --> src/bin/local_ref.rs:3:5
  |
3 |     &s
  |     ^^ returns a reference to data owned by the current function

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

E0515 는 "현재 함수가 소유한 데이터를 가리키는 참조를 돌려준다"는 뜻입니다. s 는 함수가 끝날 때 정리되므로 어떤 수명을 붙여도 그 참조는 함수 밖에서 쓸 수 없습니다. 이럴 때는 참조 대신 값 자체를 돌려주어 소유권(ownership)을 넘깁니다.

src/bin/owned.rs
// 새로 만든 값은 참조가 아니라 소유한 String 으로 돌려준다
fn greeting(name: &str) -> String {
    format!("안녕하세요, {name}님")
}

fn main() {
    let g = greeting("민지");
    println!("{g}");
}
$ cargo run --bin owned
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/owned`
안녕하세요, 민지님
C와 비교

C 컴파일러는 지역 배열의 주소를 돌려주는 함수를 컴파일해 줍니다. -Wall 을 켜면 경고만 하나 나오고, 실행 파일은 만들어집니다. 돌려받은 포인터를 읽는 순간부터 정의되지 않은 동작(undefined behavior)입니다. Rust 에서 같은 일은 경고가 아니라 오류(E0515)라서 실행 파일 자체가 생기지 않습니다.

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

/* 지역 배열의 주소를 돌려준다: 함수가 끝나면 사라지는 메모리 */
char *greeting(void) {
    char buf[32] = "안녕하세요";
    return buf;
}

int main(void) {
    char *p = greeting();
    (void)p; /* p 를 읽는 것부터 정의되지 않은 동작이라 출력하지 않는다 */
    return 0;
}
$ gcc -Wall -c dangle.c
dangle.c: In function ‘greeting’:
dangle.c:6:12: warning: function returns address of local variable [-Wreturn-local-addr]
    6 |     return buf;
      |            ^~~
핵심 정리
  • 수명은 참조가 유효하게 쓰일 수 있는 코드 구간입니다. 빌림 검사기는 빌린 값의 수명이 참조를 쓰는 구간을 덮는지 검사합니다(어기면 E0597).
  • 참조를 돌려주는 함수에서 그 참조가 어느 매개변수에서 왔는지 시그니처로 알 수 없으면 E0106 이 납니다.
  • fn f<'a>(x: &'a T, y: &'a T) -> &'a T 는 "결과는 두 입력이 모두 유효한 동안 유효하다"는 약속입니다. 수명 표시는 값을 더 오래 살게 하지 않습니다.
  • 결과와 관계없는 매개변수는 묶지 않습니다. 함수 안에서 만든 값은 참조가 아니라 소유한 값으로 돌려줍니다(E0515).
참고 공식 책 10.3절 Validating References with Lifetimes · rustc 오류 색인 E0106, E0515, E0597 · Rust Reference "Lifetime elision"
2단원

수명 생략 규칙, 참조를 담은 구조체, 'static

학습 목표
  • 수명 생략 규칙 세 가지를 말하고, 주어진 시그니처에 적용해 생략된 수명을 써 넣을 수 있다.
  • 참조를 필드로 가진 구조체와 그 impl 에 수명 매개변수를 붙일 수 있다.
  • 'static 이 무엇이고 언제 쓰는지, 오류를 덮으려고 쓰면 안 되는 이유를 설명할 수 있다.

2.1생략 규칙 세 가지

3단계의 fn first_word(s: &str) -> &str 처럼 수명을 적지 않은 함수가 많았습니다. 자주 나오는 모양은 컴파일러가 규칙대로 수명을 채우기 때문이고, 이것을 수명 생략(lifetime elision)이라 합니다. 매개변수 쪽을 입력 수명, 반환 쪽을 출력 수명이라 할 때 Rust Reference 의 규칙은 셋입니다.

규칙내용예 (생략형 → 채운 모양)
1매개변수에서 생략된 수명은 저마다 서로 다른 수명 매개변수가 된다.fn f(a: &str, b: &str) → fn f<'a, 'b>(a: &'a str, b: &'b str)
2매개변수에 쓰인 수명이 딱 하나면(생략했든 적었든), 그 수명이 생략된 모든 출력 수명에 붙는다.fn g(s: &str) -> &str → fn g<'a>(s: &'a str) -> &'a str
3메서드에서 받는 쪽(receiver)이 &self 나 &mut self 면, 그 self 참조의 수명이 생략된 모든 출력 수명에 붙는다.fn m(&self, w: &str) -> &str → 출력은 self 의 수명

규칙을 다 적용해도 출력 수명이 정해지지 않으면 컴파일러는 추측하지 않고 E0106 을 냅니다. 1.2의 first_in_dict 는 입력 수명이 둘이고 메서드도 아니라서 오류였습니다. 아래는 규칙 2와 3이 적용되는 예입니다. nth_word 의 usize 처럼 참조가 아닌 매개변수는 셈에 들어가지 않습니다.

src/bin/elide.rs
// 규칙 2: 입력 참조가 하나뿐 → 출력은 그 수명
fn first_word(s: &str) -> &str {
    s.split(' ').next().unwrap_or("")
}

// 위 함수를 컴파일러가 이해하는 모양 그대로 적으면
fn first_word_full<'a>(s: &'a str) -> &'a str {
    s.split(' ').next().unwrap_or("")
}

// 참조가 아닌 매개변수(n)는 세지 않는다 → 여전히 규칙 2
fn nth_word(s: &str, n: usize) -> &str {
    s.split(' ').nth(n).unwrap_or("")
}

struct Diary {
    entries: Vec<String>,
}

impl Diary {
    // 규칙 3: &self 가 있으면 출력은 self 의 수명
    // word 를 담은 첫 기록을 찾는다
    fn find(&self, word: &str) -> &str {
        for e in &self.entries {
            if e.contains(word) {
                return e;
            }
        }
        "없음"
    }
}

fn main() {
    println!("{}", first_word("오늘 비가 왔다"));
    println!("{}", first_word_full("내일 맑음"));
    println!("{}", nth_word("가 나 다", 2));
    let d = Diary {
        entries: vec![
            String::from("3일: 운동했다"),
            String::from("4일: 책을 읽었다"),
        ],
    };
    println!("{}", d.find("책"));
    println!("{}", d.find("영화"));
}
$ cargo run --bin elide
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/elide`
오늘
내일
다
4일: 책을 읽었다
없음

못 찾았을 때의 "없음" 은 프로그램 끝까지 유효한 리터럴(2.4절)이라 더 짧은 self 의 수명 자리에도 들어갈 수 있습니다.

규칙 2의 "수명 하나"는 Reference 의 표현입니다. 그런데 rustc 1.99.1 은 두 입력에 같은 'a 를 적고 출력만 생략하면 거절했습니다.

src/bin/same_label.rs
fn longer<'a>(a: &'a str, b: &'a str) -> &str {
    if a.len() >= b.len() { a } else { b }
}
$ cargo run --bin same_label
   Compiling errors v0.1.0 (…/p8/errors)
error[E0106]: missing lifetime specifier
 --> src/bin/same_label.rs:2:42
  |
2 | fn longer<'a>(a: &'a str, b: &'a str) -> &str {
  |                  -------     -------     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
help: consider using the `'a` lifetime
  |
2 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |                                           ++

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

이 컴파일러는 수명의 가짓수가 아니라 자리 수를 세는 듯합니다. 입력 참조가 둘 이상이면 출력 수명을 직접 적습니다.

입력 참조가 아예 없을 때는 규칙 2가 적용되지 않습니다. 이때 E0106 의 help 는 두 가지 길을 제안합니다.

src/bin/no_input.rs
fn default_name() -> &str {
    "이름 없음"
}

fn main() {
    println!("{}", default_name());
}
$ cargo run --bin no_input
   Compiling errors v0.1.0 (…/p8/errors)
error[E0106]: missing lifetime specifier
 --> src/bin/no_input.rs:1:22
  |
1 | fn default_name() -> &str {
  |                      ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
  |
1 | fn default_name() -> &'static str {
  |                       +++++++
help: instead, you are more likely to want to return an owned value
  |
1 - fn default_name() -> &str {
1 + fn default_name() -> String {
  |

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

첫째 help 는 'static 을 쓰라고 하면서 "const 나 static 에서 빌린 값을 돌려주는 경우가 아니면 드물다"고 덧붙입니다. 둘째 help 는 소유한 String 을 돌려주라고 권합니다. - 줄은 지울 줄, + 줄은 새로 넣을 줄입니다. 리터럴만 돌려준다면 첫째가 맞습니다.

2.2규칙 3과 컴파일러 help 를 비판적으로 읽기

규칙 3 때문에 메서드는 대개 수명을 적을 필요가 없습니다. 그러나 메서드가 self 가 아닌 다른 매개변수를 돌려주려 하면 규칙 3이 정한 약속(출력은 self 의 수명)과 어긋납니다. find 를 못 찾았을 때 word 를 돌려주도록 바꿔 보면 다음과 같습니다.

src/bin/rule3.rs
struct Diary {
    entries: Vec<String>,
}

impl Diary {
    // 못 찾으면 word 를 그대로 돌려주려고 한다
    fn find(&self, word: &str) -> &str {
        for e in &self.entries {
            if e.contains(word) {
                return e;
            }
        }
        word
    }
}

fn main() {
    let d = Diary { entries: vec![String::from("운동")] };
    println!("{}", d.find("책"));
}
$ cargo run --bin rule3
   Compiling errors v0.1.0 (…/p8/errors)
error: lifetime may not live long enough
  --> src/bin/rule3.rs:13:9
   |
 7 |     fn find(&self, word: &str) -> &str {
   |             -            - let's call the lifetime of this reference `'1`
   |             |
   |             let's call the lifetime of this reference `'2`
...
13 |         word
   |         ^^^^ method was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`
   |
help: consider introducing a named lifetime parameter and update trait if needed
   |
 7 |     fn find<'a>(&self, word: &'a str) -> &'a str {
   |            ++++               ++          ++

error: could not compile `errors` (bin "rule3") due to 1 previous error

이 오류에는 번호가 없습니다. 생략된 두 수명을 '1(word), '2(self)라고 부르며 '2 를 돌려줘야 하는데 '1 을 돌려준다고 설명합니다. help 대로 word 와 반환에만 'a 를 붙이면 이번에는 self 에서 나온 e 를 돌려주는 줄이 문제가 됩니다.

src/bin/help_fix.rs
impl Diary {
    // 컴파일러 help 를 그대로 따라 고친 모양
    fn find<'a>(&self, word: &'a str) -> &'a str {
        for e in &self.entries {
            if e.contains(word) {
                return e;
            }
        }
        word
    }
}
$ cargo run --bin help_fix
   Compiling errors v0.1.0 (…/p8/errors)
error: lifetime may not live long enough
  --> src/bin/help_fix.rs:10:24
   |
 7 |     fn find<'a>(&self, word: &'a str) -> &'a str {
   |             --  - let's call the lifetime of this reference `'1`
   |             |
   |             lifetime `'a` defined here
...
10 |                 return e;
   |                        ^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
   |
help: consider reusing a named lifetime parameter and update trait if needed
   |
 7 |     fn find<'a>(&'a self, word: &'a str) -> &'a str {
   |                  ++

error: could not compile `errors` (bin "help_fix") due to 1 previous error

두 번째 help 까지 따라가야 올바른 답(self 와 word 를 같은 'a 로 묶기)에 이릅니다. 결과가 어느 입력에서 나올 수 있는지는 코드를 쓴 사람이 가장 잘 압니다.

src/bin/rule3_fix.rs
struct Diary {
    entries: Vec<String>,
}

impl Diary {
    // 결과가 self 에서도, word 에서도 올 수 있다고 밝힌다
    fn find<'a>(&'a self, word: &'a str) -> &'a str {
        for e in &self.entries {
            if e.contains(word) {
                return e;
            }
        }
        word
    }
}

fn main() {
    let d = Diary { entries: vec![String::from("운동")] };
    println!("{}", d.find("운"));
    println!("{}", d.find("책"));
}
$ cargo run --bin rule3_fix
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/rule3_fix`
운동
책

2.3참조를 필드로 가진 구조체

구조체(struct)가 참조를 필드로 가지면, 그 구조체 값은 빌려 온 원본보다 오래 살 수 없습니다. 이 관계를 표시하려면 구조체 이름 뒤에 수명 매개변수를 선언하고 필드에 붙여야 합니다. 빠뜨리면 E0106 이 납니다(구조체 정의에는 생략 규칙이 없습니다).

$ cargo run --bin struct_no_label
   Compiling errors v0.1.0 (…/p8/errors)
error[E0106]: missing lifetime specifier
 --> src/bin/struct_no_label.rs:3:12
  |
3 |     quote: &str,
  |            ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 ~ struct Bookmark<'a> {
2 |     page: u32,
3 ~     quote: &'a str,
  |

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

아래 Bookmark<'a> 는 책 본문의 한 부분을 가리키는 책갈피입니다. impl 에도 impl<'a> Bookmark<'a> 처럼 수명을 선언합니다. 제네릭 구조체의 impl<T> 와 같은 모양입니다.

src/bin/bookmark.rs
// 책 본문의 한 부분을 가리키는 책갈피
#[derive(Debug)]
struct Bookmark<'a> {
    page: u32,
    quote: &'a str,
}

impl<'a> Bookmark<'a> {
    // 규칙 3 덕분에 반환 수명을 적지 않아도 된다
    fn first_char(&self) -> &str {
        match self.quote.char_indices().nth(1) {
            Some((i, _)) => &self.quote[..i],
            None => self.quote,
        }
    }

    // 돌려주는 참조가 책 본문을 가리킨다고 밝힌다
    fn quote(&self) -> &'a str {
        self.quote
    }
}

fn main() {
    let book = String::from("하늘과 바람과 별과 시. 서시.");
    let end = book.find('.').unwrap_or(book.len());
    let q;
    {
        let mark = Bookmark { page: 12, quote: &book[..end] };
        println!("{mark:?}");
        println!("{}쪽 첫 글자: {}", mark.page, mark.first_char());
        q = mark.quote();
    } // 책갈피는 여기서 사라져도
    println!("인용: {q}"); // 본문은 아직 살아 있다
}
$ cargo run --bin bookmark
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/bookmark`
Bookmark { page: 12, quote: "하늘과 바람과 별과 시" }
12쪽 첫 글자: 하
인용: 하늘과 바람과 별과 시

first_char 는 수명을 생략했으므로 규칙 3에 따라 결과가 책갈피(&self)를 빌린 동안만 유효합니다. quote 는 &'a str 로 적었으므로 책 본문('a)이 살아 있는 동안 유효하고, 그래서 mark 가 사라진 뒤에도 q 를 쓸 수 있습니다. quote 의 반환을 &str 로 생략하면 같은 main 이 컴파일되지 않습니다.

$ cargo run --bin bookmark_elided
   Compiling errors v0.1.0 (…/p8/errors)
error[E0597]: `mark` does not live long enough
  --> src/bin/bookmark_elided.rs:31:13
   |
28 |         let mark = Bookmark { page: 12, quote: &book[..end] };
   |             ---- binding `mark` declared here
...
31 |         q = mark.quote();
   |             ^^^^ borrowed value does not live long enough
32 |     } // 책갈피는 여기서 사라져도
   |     - `mark` dropped here while still borrowed
33 |     println!("인용: {q}"); // 본문은 아직 살아 있다
   |                      - borrow later used here

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

이번에 빌림이 부족한 값은 book 이 아니라 mark 입니다. 생략 규칙이 결과를 mark 를 빌린 것으로 만들었기 때문입니다. 반대로 원본이 구조체보다 먼저 사라지면 원본 쪽에서 E0597 이 납니다.

src/bin/mark_outlives.rs
#[derive(Debug)]
struct Bookmark<'a> {
    page: u32,
    quote: &'a str,
}

fn main() {
    let mark;
    {
        let book = String::from("별 헤는 밤");
        mark = Bookmark { page: 3, quote: &book[..] };
    }
    println!("{mark:?}");
}
$ cargo run --bin mark_outlives
   Compiling errors v0.1.0 (…/p8/errors)
error[E0597]: `book` does not live long enough
  --> src/bin/mark_outlives.rs:11:44
   |
10 |         let book = String::from("별 헤는 밤");
   |             ---- binding `book` declared here
11 |         mark = Bookmark { page: 3, quote: &book[..] };
   |                                            ^^^^ borrowed value does not live long enough
12 |     }
   |     - `book` dropped here while still borrowed
13 |     println!("{mark:?}");
   |                ---- borrow later used here

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

2.4'static: 프로그램이 끝날 때까지

'static 은 "프로그램이 실행되는 내내 유효하다"는 뜻의 특별한 수명입니다. 문자열 리터럴의 글자는 실행 파일 안에 들어 있어 타입이 &'static str 입니다. static·const 로 선언한 참조 타입도 수명을 적지 않으면 'static 입니다.

src/bin/statics.rs
// 문자열 리터럴은 프로그램 파일 안에 들어 있어서 끝까지 산다
fn grade_name(score: u32) -> &'static str {
    match score {
        90..=100 => "수",
        80..=89 => "우",
        70..=79 => "미",
        _ => "노력 요함",
    }
}

static SCHOOL: &str = "한빛고등학교";

fn main() {
    let g;
    {
        let score = 85;
        g = grade_name(score);
    } // score 는 사라져도 g 는 멀쩡하다
    println!("{SCHOOL} 성적: {g}");
}
$ cargo run --bin statics
   Compiling life v0.1.0 (…/p8/life)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/statics`
한빛고등학교 성적: 우

score 는 블록 안에서 사라졌지만 g 는 score 를 빌린 것이 아니라 리터럴을 가리키므로 문제가 없습니다. 시그니처의 &'static str 덕분에 부르는 쪽도 그 사실을 압니다.

흔한 실수

E0597 이나 E0106 이 나오면 'static 을 붙여 덮고 싶어집니다. 하지만 'static 은 "끝까지 산다"는 강한 약속이라, 매개변수나 지역 변수를 빌린 참조에는 붙일 수 없습니다. 붙여 보면 이번에는 "'1 이 'static 보다 오래 살아야 한다"는 오류로 바뀔 뿐입니다.

src/bin/static_wrong.rs
// 오류를 덮으려고 'static 을 붙여 본다
fn first_line(text: &String) -> &'static str {
    text.lines().next().unwrap_or("")
}

fn main() {
    let memo = String::from("우유 사기\n빨래");
    println!("{}", first_line(&memo));
}
$ cargo run --bin static_wrong
   Compiling errors v0.1.0 (…/p8/errors)
error: lifetime may not live long enough
 --> src/bin/static_wrong.rs:3:5
  |
2 | fn first_line(text: &String) -> &'static str {
  |                     - let's call the lifetime of this reference `'1`
3 |     text.lines().next().unwrap_or("")
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'static`

error: could not compile `errors` (bin "static_wrong") due to 1 previous error

해결책은 원본을 더 오래 살게 하거나, 결과를 입력과 묶거나(이 예는 규칙 2 그대로), 소유한 값(String)을 쓰는 것입니다.

핵심 정리
  • 생략 규칙: (1) 입력의 생략된 수명은 저마다 다른 수명, (2) 입력 수명이 하나면 출력도 그것, (3) &self/&mut self 가 있으면 출력은 self 의 수명. 그래도 정해지지 않으면 E0106.
  • 컴파일러 help 의 수명 제안은 출발점일 뿐입니다. 결과가 어느 입력에서 나오는지 스스로 따져 묶습니다.
  • 참조를 담은 구조체는 struct S<'a>, impl<'a> S<'a> 로 수명을 선언합니다. 값은 원본보다 오래 살 수 없습니다.
  • 'static 은 프로그램 끝까지 유효한 참조(문자열 리터럴 등)의 수명입니다. 오류를 덮는 용도로 쓰지 않습니다.
참고 Rust Reference "Lifetime elision" · 공식 책 10.3절 · std 문서 primitive str
3단원

Box<T>, Deref, Drop

학습 목표
  • 스마트 포인터(smart pointer)가 무엇인지, Box<T> 가 메모리에 어떻게 놓이는지 설명할 수 있다.
  • 재귀 타입이 E0072 를 내는 이유를 알고 Box 로 고칠 수 있다.
  • Deref 를 구현해 * 연산과 역참조 강제 변환을 쓸 수 있다.
  • Drop 으로 정리 코드를 넣고, 값이 정리되는 순서를 예측할 수 있다.

3.1스마트 포인터와 Box<T>

스마트 포인터는 참조처럼 값을 가리키면서, 그 값을 소유하거나 주인 수를 세는 등 기능을 더한 구조체입니다. 6단계의 String, Vec<T> 도 힙 데이터를 소유하는 스마트 포인터입니다.

가장 단순한 것이 Box<T> 입니다. Box::new(v) 는 v 를 힙에 옮겨 놓고, 그 주소를 담은 상자를 돌려줍니다. 상자 자체는 보통 지역 변수로 스택에 놓이고 크기는 주소 하나뿐입니다. 상자가 범위를 벗어나면 힙의 값도 함께 정리됩니다.

src/bin/box_basic.rs
fn main() {
    let score = Box::new(87); // 87 은 힙에, 상자(주소)는 스택에
    println!("점수: {score}");
    println!("10점 더하면: {}", *score + 10);

    let big = Box::new([0u8; 1000]); // 큰 배열도 힙으로
    println!("배열 길이: {}", big.len());
    println!("상자 크기: {}바이트", size_of::<Box<[u8; 1000]>>());
} // score 와 big 이 사라지면서 힙 메모리도 돌려준다
$ cargo run --bin box_basic
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/box_basic`
점수: 87
10점 더하면: 97
배열 길이: 1000
상자 크기: 8바이트

size_of::<T>() 는 타입의 크기(바이트)를 알려 줍니다. 천 바이트 배열을 담은 상자도 이 컴퓨터(64비트)에서는 주소 하나 크기인 8바이트입니다. *score 로 안의 값을 꺼냅니다(println! 에서는 * 없이도 됨).

스택 힙 score: 주소 (8바이트) 87 (i32) score 가 범위를 벗어나면 → 힙의 87 도 정리된다
그림 2. let score = Box::new(87); 직후의 메모리. 상자는 힙의 값을 소유한다.

3.2재귀 타입에는 Box 가 필요하다

Box 가 꼭 필요한 대표적인 경우는 자기 자신을 안에 담는 타입입니다. "(2 + 3) * 4" 같은 계산식을 열거형(enum)으로 나타내 봅시다. 식은 수 하나이거나, 두 식의 덧셈·곱셈입니다.

src/bin/expr_nobox.rs
// 계산식: 수 하나이거나, 두 식의 덧셈·곱셈
enum Expr {
    Num(i64),
    Add(Expr, Expr),
    Mul(Expr, Expr),
}

fn main() {
    let e = Expr::Num(3);
}
$ cargo run --bin expr_nobox
   Compiling errors v0.1.0 (…/p8/errors)
error[E0072]: recursive type `Expr` has infinite size
 --> src/bin/expr_nobox.rs:2:1
  |
2 | enum Expr {
  | ^^^^^^^^^
3 |     Num(i64),
4 |     Add(Expr, Expr),
  |         ---- recursive without indirection
  |
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
  |
4 |     Add(Box<Expr>, Expr),
  |         ++++    +

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

Rust 는 컴파일할 때 모든 타입의 크기를 알아야 합니다. Expr 의 크기를 구하려면 안에 든 Expr 의 크기가 필요하고, 그 안에 또 Expr 가 있으니 끝이 없습니다(E0072). help 는 간접 참조(indirection), 즉 값 대신 크기가 정해진 포인터를 넣으라고 합니다.

src/bin/expr.rs
// 계산식: 수 하나이거나, 두 식의 덧셈·곱셈
enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
}

fn eval(e: &Expr) -> i64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => eval(a) + eval(b),
        Expr::Mul(a, b) => eval(a) * eval(b),
    }
}

fn show(e: &Expr) -> String {
    match e {
        Expr::Num(n) => n.to_string(),
        Expr::Add(a, b) => format!("({} + {})", show(a), show(b)),
        Expr::Mul(a, b) => format!("{} * {}", show(a), show(b)),
    }
}

fn num(n: i64) -> Box<Expr> {
    Box::new(Expr::Num(n))
}

fn main() {
    // (2 + 3) * 4
    let e = Expr::Mul(Box::new(Expr::Add(num(2), num(3))), num(4));
    println!("{} = {}", show(&e), eval(&e));
    println!("Expr 크기: {}바이트", size_of::<Expr>());
}
$ cargo run --bin expr
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/expr`
(2 + 3) * 4 = 20
Expr 크기: 24바이트

이제 Add 는 상자 두 개만 담으므로 크기가 정해집니다. 이 컴퓨터에서는 24바이트였습니다. 상자 둘이 16바이트이니 나머지는 변형(variant)을 구별하는 값과 정렬용 빈칸으로 짐작됩니다(배치는 컴파일러가 정하며 보장되지 않습니다). eval(a) 에서 &Box<Expr> 를 &Expr 자리에 넘길 수 있는 것은 3.3절의 역참조 강제 변환 덕분입니다.

한 줄로 이어지는 목록도 같은 원리입니다. 노래 하나가 "다음 노래가 있으면 그 상자"를 들고 있게 하면 Option<Box<Song>> 이 됩니다. as_deref() 는 Option<Box<Song>> 을 빌려 Option<&Song> 으로 보여 주는 메서드입니다.

src/bin/playlist.rs
// 노래 목록: 한 곡이 다음 곡 상자를 들고 있다
struct Song {
    title: String,
    next: Option<Box<Song>>,
}

fn main() {
    let list = Song {
        title: String::from("봄날"),
        next: Some(Box::new(Song {
            title: String::from("밤편지"),
            next: Some(Box::new(Song {
                title: String::from("좋은 날"),
                next: None,
            })),
        })),
    };

    let mut cur = Some(&list);
    let mut n = 1;
    while let Some(song) = cur {
        println!("{n}. {}", song.title);
        cur = song.next.as_deref();
        n += 1;
    }
}
$ cargo run --bin playlist
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/playlist`
1. 봄날
2. 밤편지
3. 좋은 날
C와 비교

C 에서는 구조체 안에 자기 타입의 포인터를 넣고 malloc 으로 노드를 만듭니다. 생각은 Box 와 같지만, 다 쓴 노드를 하나하나 free 하는 코드(free_expr)를 직접 써야 하고, 빠뜨리면 누수, 두 번 하면 이중 해제입니다. Rust 의 Box 는 주인이 범위를 벗어날 때 안쪽 상자까지 차례로 정리합니다.

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

/* 계산식 노드: 자기 자신을 가리키는 포인터를 가진다 */
struct Expr {
    int kind;            /* 0: 수, 1: 덧셈 */
    long num;
    struct Expr *a, *b;
};

struct Expr *num(long n) {
    struct Expr *e = malloc(sizeof *e);
    e->kind = 0; e->num = n; e->a = e->b = NULL;
    return e;
}

long eval(const struct Expr *e) {
    return e->kind == 0 ? e->num : eval(e->a) + eval(e->b);
}

void free_expr(struct Expr *e) { /* 직접 하나하나 풀어야 한다 */
    if (e->kind == 1) { free_expr(e->a); free_expr(e->b); }
    free(e);
}

int main(void) {
    struct Expr *sum = malloc(sizeof *sum);
    sum->kind = 1; sum->a = num(2); sum->b = num(3);
    printf("2 + 3 = %ld\n", eval(sum));
    free_expr(sum);
    return 0;
}
$ gcc -Wall -o node node.c && ./node
2 + 3 = 5

3.3Deref: * 연산자와 역참조 강제 변환

*x 는 "x 가 가리키는 값"을 뜻합니다. 참조에는 원래 쓸 수 있고, 내가 만든 타입에는 std::ops::Deref 트레이트(trait)를 구현해야 쓸 수 있습니다. 구현하지 않은 타입에 * 를 쓰면 E0614 가 납니다.

src/bin/no_deref.rs
struct Tagged<T> {
    tag: &'static str,
    value: T,
}

fn main() {
    let age = Tagged { tag: "나이", value: 17 };
    println!("{}: {}", age.tag, *age);
}
$ cargo run --bin no_deref
   Compiling errors v0.1.0 (…/p8/errors)
error[E0614]: type `Tagged<{integer}>` cannot be dereferenced
 --> src/bin/no_deref.rs:8:33
  |
8 |     println!("{}: {}", age.tag, *age);
  |                                 ^^^^ can't be dereferenced

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

Deref 는 Target(가리키는 대상 타입)과 deref(&self) -> &Target 로 이루어집니다. 아래 Tagged<T> 는 값에 이름표를 붙인 작은 스마트 포인터입니다.

src/bin/deref.rs
use std::ops::Deref;

// 값에 이름표를 붙여 들고 다니는 상자
struct Tagged<T> {
    tag: &'static str,
    value: T,
}

impl<T> Tagged<T> {
    fn new(tag: &'static str, value: T) -> Tagged<T> {
        Tagged { tag, value }
    }
}

impl<T> Deref for Tagged<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.value
    }
}

fn count_chars(s: &str) -> usize {
    s.chars().count()
}

fn main() {
    let age = Tagged::new("나이", 17);
    println!("{}: {}", age.tag, *age);   // *age 는 *(age.deref())
    println!("내년: {}", *age + 1);

    let name = Tagged::new("이름", String::from("이서연"));
    // &Tagged<String> → &String → &str 로 저절로 바뀐다
    println!("{} 글자 수: {}", name.tag, count_chars(&name));
    println!("바이트 수: {}", name.len()); // String 의 메서드
}
$ cargo run --bin deref
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/deref`
나이: 17
내년: 18
이름 글자 수: 3
바이트 수: 9

*age 라고 쓰면 컴파일러는 이것을 *(age.deref()) 로 바꿉니다. deref 가 참조를 돌려주고, 그 참조에 보통의 * 를 적용하는 것입니다. deref 가 값이 아니라 참조를 돌려주는 이유는, 값을 돌려주면 Tagged 안의 값이 밖으로 이동(move)해 버리기 때문입니다.

더 편리한 기능은 역참조 강제 변환(deref coercion)입니다. 타입이 정해진 자리(함수 인자 등)에 &Tagged<String> 을 넘기면 컴파일러가 deref 를 이어 불러 &String → &str 로 바꿉니다(String 도 Target = str 인 Deref 를 구현합니다). name.len() 도 같은 원리입니다. 가변 참조 쪽은 DerefMut 가 맡습니다.

3.4Drop: 정리 코드와 정리 순서

값이 범위를 벗어날 때 실행할 코드를 넣고 싶으면 Drop 트레이트의 drop(&mut self) 메서드를 구현합니다. Box 가 힙 메모리를 돌려주는 것, 파일이 닫히는 것도 모두 Drop 으로 이루어집니다. 정리될 때 이름을 말하는 Noisy 로 순서를 확인해 봅시다.

src/bin/drop_order.rs
// 사라질 때 이름을 말하는 값
struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("  정리: {}", self.0);
    }
}

struct Pair {
    left: Noisy,
    right: Noisy,
}

fn main() {
    println!("main 시작");
    let _a = Noisy("a");
    let _b = Noisy("b");
    {
        let _c = Noisy("c (안쪽 블록)");
        println!("안쪽 블록 끝");
    }
    let p = Pair { left: Noisy("p.left"), right: Noisy("p.right") };
    let v = vec![Noisy("v[0]"), Noisy("v[1]")];
    let early = Noisy("early");
    drop(early); // 미리 정리
    println!("main 끝 ({}, {}, 벡터 {}개)", p.left.0, p.right.0, v.len());
}
$ cargo run --bin drop_order
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/drop_order`
main 시작
안쪽 블록 끝
  정리: c (안쪽 블록)
  정리: early
main 끝 (p.left, p.right, 벡터 2개)
  정리: v[0]
  정리: v[1]
  정리: p.left
  정리: p.right
  정리: b
  정리: a

결과에서 읽을 수 있는 규칙은 다음과 같습니다. Rust Reference 의 "Destructors" 장에 적힌 규칙과 일치합니다.

  • 블록이 끝나면 그 블록의 변수는 선언의 역순으로 정리됩니다: v → p → _b → _a. 안쪽 블록의 _c 는 그 블록이 끝날 때 바로 정리됩니다.
  • 구조체의 필드는 선언 순서대로 정리됩니다: p.left → p.right.
  • drop(early) 처럼 표준 함수 drop 에 값을 넘기면 소유권이 넘어가 그 자리에서 정리됩니다. 이미 넘어간 값이므로 블록 끝에서 다시 정리되지 않습니다.
  • 벡터의 원소는 이번 실행에서 앞에서부터 정리되었지만, Vec 문서는 원소 정리 순서를 보장하지 않는다고 밝힙니다. 순서에 기대는 코드를 쓰지 않는 것이 좋습니다.

drop 메서드를 직접 부를 수는 없습니다. 직접 부른 뒤 블록 끝에서 또 불리면 같은 자원을 두 번 정리하게 되기 때문입니다.

src/bin/call_drop.rs
fn main() {
    let n = Noisy("n");
    n.drop();
}
$ cargo run --bin call_drop
   Compiling errors v0.1.0 (…/p8/errors)
error[E0040]: explicit use of destructor method
  --> src/bin/call_drop.rs:11:7
   |
11 |     n.drop();
   |       ^^^^ explicit destructor calls not allowed
   |
help: consider using `drop` function
   |
11 -     n.drop();
11 +     drop(n);
   |

For more information about this error, try `rustc --explain E0040`.
error: could not compile `errors` (bin "call_drop") due to 1 previous error
흔한 실수

_ 는 아무것도 묶지 않는 패턴입니다. 새로 만든 값을 let _ = 값; 으로 받으면 그 문장 끝에서 정리되고, 이미 있는 변수는 let _ = x; 해도 옮겨지지도 정리되지도 않습니다. 반면 let _kept = 값; 처럼 밑줄로 시작하는 이름은 보통 변수라서 블록 끝까지 삽니다. 잠금(10단계의 뮤텍스)처럼 "들고 있는 동안만 효과가 있는 값"을 _ 로 받으면 곧바로 풀려 버립니다.

src/bin/underscore.rs
fn main() {
    let _kept = Noisy("_kept");
    let x = Noisy("x");
    let _ = x; // 이미 있는 변수: 옮기지도 정리하지도 않는다
    let _ = Noisy("_ 에 맡긴 새 값"); // 이 문장 끝에서 정리
    println!("main 끝");
}
$ cargo run --bin underscore
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/underscore`
  정리: _ 에 맡긴 새 값
main 끝
  정리: x
  정리: _kept
핵심 정리
  • 스마트 포인터는 값을 가리키면서 소유 등 추가 기능을 가진 구조체입니다. Box<T> 는 값을 힙에 두고 혼자 소유합니다.
  • 자기 자신을 담는 타입은 크기를 정할 수 없어 E0072 가 납니다. Box 로 간접 참조를 넣어 해결합니다.
  • Deref 를 구현하면 * 를 쓸 수 있고, 역참조 강제 변환으로 &Box<T>, &String 등이 필요한 참조 타입으로 저절로 바뀝니다.
  • Drop 은 정리 코드를 넣는 트레이트입니다. 변수는 선언 역순, 필드는 선언 순서로 정리됩니다. 미리 정리하려면 drop(값) 을 씁니다(E0040).
참고 공식 책 15.1~15.3절 · std 문서 Box, std::ops::Deref, std::ops::Drop, Vec(Guarantees) · Rust Reference "Destructors" · rustc 오류 색인 E0072, E0040, E0614
4단원

Rc<T> 와 RefCell<T>

학습 목표
  • Rc<T> 로 한 값에 주인 여럿을 두고, Rc::clone 과 Rc::strong_count 의 동작을 설명할 수 있다.
  • 내부 가변성(interior mutability)이 무엇이고 RefCell<T> 가 빌림 규칙을 언제 검사하는지 설명할 수 있다.
  • Rc<RefCell<T>> 로 여러 주인이 함께 고치는 값을 만들 수 있다.

4.1주인이 여럿 필요할 때: Rc<T>

값의 주인은 하나입니다. 공지 하나를 두 게시판이 함께 거는 것처럼 누가 마지막까지 쓸지 정할 수 없는 공유를 그대로 쓰면 E0382 가 납니다.

src/bin/two_owners.rs
struct Notice {
    text: String,
}

struct Board {
    name: &'static str,
    notice: Notice,
}

fn main() {
    let n = Notice { text: String::from("금요일 휴관") };
    let hall = Board { name: "1층", notice: n };
    let lobby = Board { name: "로비", notice: n };
    println!("{} {}", hall.name, lobby.name);
}
$ cargo run --bin two_owners
   Compiling errors v0.1.0 (…/p8/errors)
error[E0382]: use of moved value: `n`
  --> src/bin/two_owners.rs:13:45
   |
11 |     let n = Notice { text: String::from("금요일 휴관") };
   |         - move occurs because `n` has type `Notice`, which does not implement the `Copy` trait
12 |     let hall = Board { name: "1층", notice: n };
   |                                             - value moved here
13 |     let lobby = Board { name: "로비", notice: n };
   |                                               ^ value used here after move
   |
note: if `Notice` implemented `Clone`, you could clone the value
  --> src/bin/two_owners.rs:1:1
   |
 1 | struct Notice {
   | ^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
12 |     let hall = Board { name: "1층", notice: n };
   |                                             - you could clone this value

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

Rc<T>(reference counting, 참조 세기)는 값을 힙에 두고 주인이 몇인지 센 수를 함께 둡니다. Rc::clone(&r) 은 값을 복사하지 않고 수만 1 올린 새 포인터를 만들고, Rc 하나가 정리될 때마다 수가 1 내려갑니다. 수가 0이 되는 순간 값이 정리됩니다.

src/bin/rc_count.rs
use std::rc::Rc;

// 도서관 공지 하나를 여러 게시판이 함께 가진다
struct Board {
    name: &'static str,
    notice: Rc<String>,
}

fn main() {
    let notice = Rc::new(String::from("금요일 휴관"));
    println!("처음: 주인 {}명", Rc::strong_count(&notice));

    let hall = Board { name: "1층", notice: Rc::clone(&notice) };
    println!("1층 게시: 주인 {}명", Rc::strong_count(&notice));
    {
        let lobby = Board { name: "로비", notice: Rc::clone(&notice) };
        println!("로비 게시: 주인 {}명", Rc::strong_count(&notice));
        println!("{} → {}", lobby.name, lobby.notice);
    } // lobby 가 사라지며 수가 하나 준다
    println!("로비 철거: 주인 {}명", Rc::strong_count(&notice));
    println!("{} → {}", hall.name, hall.notice);
    println!("같은 값? {}", Rc::ptr_eq(&notice, &hall.notice));
}
$ cargo run --bin rc_count
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/rc_count`
처음: 주인 1명
1층 게시: 주인 2명
로비 게시: 주인 3명
로비 → 금요일 휴관
로비 철거: 주인 2명
1층 → 금요일 휴관
같은 값? true

r.clone() 이라고 써도 같은 일을 하지만, 깊은 복사를 하는 다른 타입의 clone 과 구별되도록 Rc::clone(&r) 으로 쓰는 관례가 있습니다. Rc::ptr_eq 는 두 Rc 가 같은 값을 가리키는지 확인합니다.

스택 힙 (한 덩어리) notice hall.notice lobby.notice strong 칸: 3 weak 칸: 1 (아래 설명) 값: String "금요일 휴관" String 의 글자들은 힙의 또 다른 곳에 있다 (그림에서는 생략)
그림 3. lobby 가 있을 때의 모습. Rc 셋이 한 덩어리를 가리키고, 덩어리 안에 센 수 두 칸과 값이 함께 있다. weak 칸에는 strong 들의 몫 1이 더해져 있어 Weak 가 없으면 Rc::weak_count 는 0이다.

Rc 로 공유한 값은 보통 불변으로만 빌릴 수 있습니다. 주인이 여럿인데 아무나 고칠 수 있다면 "가변 참조는 하나뿐"이라는 규칙이 깨지기 때문입니다. Rc 는 Deref 는 구현하지만 DerefMut 는 구현하지 않는다고 help 가 알려 줍니다.

src/bin/rc_mut.rs
use std::rc::Rc;

fn main() {
    let notice = Rc::new(String::from("금요일 휴관"));
    let copy = Rc::clone(&notice);
    copy.push_str(" (토요일 정상)");
    println!("{notice}");
}
$ cargo run --bin rc_mut
   Compiling errors v0.1.0 (…/p8/errors)
error[E0596]: cannot borrow data in an `Rc` as mutable
 --> src/bin/rc_mut.rs:6:5
  |
6 |     copy.push_str(" (토요일 정상)");
  |     ^^^^ cannot borrow as mutable
  |
  = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<String>`

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

또 Rc 의 수 세기는 한 스레드(thread) 안에서만 안전하도록 만들어져 있습니다. 여러 스레드가 공유할 때 쓰는 Arc<T> 는 10단계에서 배웁니다.

4.2내부 가변성과 RefCell<T>

빌림 규칙(가변 참조 하나 또는 불변 참조 여럿)은 보통 컴파일할 때 검사됩니다. RefCell<T> 는 같은 규칙을 실행 중에 검사하는 대신, &RefCell<T> 라는 불변 참조만 가지고도 안의 값을 고칠 수 있게 해 줍니다. 겉은 불변인데 안을 고칠 수 있다고 해서 이것을 내부 가변성(interior mutability)이라 부릅니다.

  • borrow() 는 읽기용 빌림(Ref<T>)을, borrow_mut() 는 쓰기용 빌림(RefMut<T>)을 돌려줍니다. 둘 다 Deref 를 구현해 참조처럼 쓰입니다.
  • RefCell 은 지금 살아 있는 읽기·쓰기 빌림의 수를 셉니다. 빌림 값이 정리되면(Drop) 수가 줄어듭니다.
  • 규칙을 어기는 빌림을 요청하면 컴파일 오류가 아니라 패닉(panic)이 납니다.

&self 만 받는 계산 메서드가 기록을 남기는 예입니다.

src/bin/refcell_log.rs
use std::cell::RefCell;

// &self 만 받는데도 기록을 남기고 싶은 계산기
struct Calculator {
    history: RefCell<Vec<String>>,
}

impl Calculator {
    fn add(&self, a: i32, b: i32) -> i32 {
        let r = a + b;
        self.history.borrow_mut().push(format!("{a} + {b} = {r}"));
        r
    }
}

fn main() {
    let calc = Calculator { history: RefCell::new(Vec::new()) };
    calc.add(2, 3);
    calc.add(10, 20);
    for line in calc.history.borrow().iter() {
        println!("{line}");
    }
    println!("기록 {}개", calc.history.borrow().len());
}
$ cargo run --bin refcell_log
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/refcell_log`
2 + 3 = 5
10 + 20 = 30
기록 2개

self.history.borrow_mut().push(…) 의 RefMut 는 그 문장이 끝나면 정리되므로 쓰기 빌림이 오래 남지 않습니다. 이제 규칙을 일부러 어겨 봅시다. 읽기 빌림 reader 가 살아 있는 동안 쓰기 빌림을 요청합니다.

src/bin/refcell_panic.rs
use std::cell::RefCell;

fn main() {
    let scores = RefCell::new(vec![80, 95]);
    let reader = scores.borrow(); // 읽기 빌림이 살아 있는 동안
    println!("첫 점수: {}", reader[0]);
    scores.borrow_mut().push(70); // 쓰기 빌림을 또 요청
    println!("여기까지 오지 않는다");
}
$ cargo run --bin refcell_panic
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/refcell_panic`
첫 점수: 80

thread 'main' (…) panicked at src/bin/refcell_panic.rs:7:12:
RefCell already borrowed
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

컴파일은 통과했고, 실행 중 7번째 줄에서 RefCell already borrowed 라는 메시지와 함께 패닉이 났습니다. thread 'main' (…) 의 괄호 안에는 실행마다 달라지는 스레드 번호가 들어가서 여기서는 줄였습니다. 패닉 대신 실패를 값으로 받고 싶으면 try_borrow_mut() 를 씁니다. 5단계의 Result 를 돌려줍니다.

src/bin/refcell_try.rs
use std::cell::RefCell;

fn main() {
    let scores = RefCell::new(vec![80, 95]);
    {
        let reader = scores.borrow();
        match scores.try_borrow_mut() {
            Ok(_) => println!("쓰기 성공"),
            Err(e) => println!("지금은 못 씀: {e}"),
        }
        println!("읽는 중: {:?}", *reader);
    } // reader 가 사라졌다
    scores.borrow_mut().push(70);
    println!("이제: {:?}", scores.borrow());
}
$ cargo run --bin refcell_try
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/refcell_try`
지금은 못 씀: RefCell already borrowed
읽는 중: [80, 95]
이제: [80, 95, 70]
빌림 없음
→
borrow() 여럿읽기 수 1, 2, …
→
이때 borrow_mut()패닉 / try_ 는 Err
빌림 없음
→
borrow_mut() 하나쓰기 중
→
이때 borrow() 나 borrow_mut()패닉 / try_ 는 Err
왜 이렇게 만들었을까

컴파일 중 검사는 보수적이라 안전해도 증명할 수 없으면 거절합니다. RefCell 은 그 검사를 실행 중으로 미룹니다. 대신 세는 비용이 들고 실수가 실행 중에야 드러나므로 꼭 필요한 곳에만 씁니다.

4.3Rc<RefCell<T>>: 함께 갖고 함께 고치기

Rc 는 주인을 여럿 두지만 고칠 수 없고, RefCell 은 고칠 수 있지만 주인은 하나입니다. 둘을 겹친 Rc<RefCell<T>> 는 여러 주인이 같은 값을 고칠 수 있게 합니다. 엄마와 아들이 가계부 하나를 함께 쓰는 예입니다.

src/bin/shared_book.rs
use std::cell::RefCell;
use std::rc::Rc;

// 두 사람이 함께 쓰는 가계부
struct Ledger {
    items: Vec<(String, i32)>,
}

struct Person {
    name: &'static str,
    book: Rc<RefCell<Ledger>>,
}

impl Person {
    fn spend(&self, what: &str, won: i32) {
        self.book.borrow_mut().items.push((what.to_string(), won));
        println!("{}: {what} {won}원 기록", self.name);
    }
}

fn main() {
    let book = Rc::new(RefCell::new(Ledger { items: Vec::new() }));
    let mom = Person { name: "엄마", book: Rc::clone(&book) };
    let son = Person { name: "아들", book: Rc::clone(&book) };

    mom.spend("장보기", 32000);
    son.spend("문제집", 15000);
    mom.spend("전기 요금", 41000);

    let mut total = 0;
    for (_, won) in book.borrow().items.iter() {
        total += won;
    }
    println!("항목 {}개, 합계 {total}원", book.borrow().items.len());
    println!("가계부 주인 {}명", Rc::strong_count(&book));
}
$ cargo run --bin shared_book
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/shared_book`
엄마: 장보기 32000원 기록
아들: 문제집 15000원 기록
엄마: 전기 요금 41000원 기록
항목 3개, 합계 88000원
가계부 주인 3명

self.book.borrow_mut() 에서 메서드 호출이 Rc 를 저절로 역참조해 RefCell 의 메서드를 부르고, 얻은 RefMut<Ledger> 로 items 에 접근합니다. 주인 3명은 book, mom.book, son.book 입니다.

핵심 정리
  • Rc<T> 는 주인 수를 세는 공유 소유 포인터입니다. Rc::clone 은 수를 올리고, 정리될 때 수가 내려가며, 0이면 값이 정리됩니다.
  • Rc 를 통해서는 보통 값을 고칠 수 없습니다(E0596). 한 스레드 전용이며 여러 스레드용은 Arc 입니다.
  • RefCell<T> 는 빌림 규칙을 실행 중에 검사해 불변 참조로도 안을 고치게 합니다. 어기면 패닉, try_borrow_mut 는 Err.
  • Rc<RefCell<T>> 는 여러 주인이 함께 고치는 값을 만드는 흔한 조합입니다.
참고 공식 책 15.4~15.5절 · std 문서 std::rc::Rc, std::cell::RefCell, std::cell 모듈 설명 · rustc 오류 색인 E0596
5단원

Weak 와 순환 참조

학습 목표
  • Rc 끼리 서로 가리키면 메모리가 정리되지 않는 이유를 센 수로 설명할 수 있다.
  • Weak<T> 와 Rc::downgrade, upgrade 로 순환을 끊을 수 있다.
  • 상황에 맞는 스마트 포인터를 고를 수 있다.

5.1서로 가리키면 수가 0이 되지 않는다

짝꿍을 서로 가리키는 두 학생을 Rc 로 만들어 봅시다. Drop 을 구현해 정리될 때 이름을 출력하게 했습니다.

src/bin/cycle_leak.rs
use std::cell::RefCell;
use std::rc::Rc;

// 짝꿍을 서로 가리키는 학생
struct Student {
    name: &'static str,
    buddy: RefCell<Option<Rc<Student>>>,
}

impl Drop for Student {
    fn drop(&mut self) {
        println!("  정리: {}", self.name);
    }
}

fn main() {
    let a = Rc::new(Student { name: "민지", buddy: RefCell::new(None) });
    let b = Rc::new(Student { name: "준호", buddy: RefCell::new(None) });
    *a.buddy.borrow_mut() = Some(Rc::clone(&b));
    *b.buddy.borrow_mut() = Some(Rc::clone(&a));
    println!("민지 주인 {}명, 준호 주인 {}명",
             Rc::strong_count(&a), Rc::strong_count(&b));
    println!("main 끝");
} // a, b 가 사라져도 수가 1 씩 남는다 → 정리되지 않음
$ cargo run --bin cycle_leak
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/cycle_leak`
민지 주인 2명, 준호 주인 2명
main 끝

"정리" 줄이 없습니다. main 끝에서 b, a 가 정리되며 수가 2에서 1로 내려가지만, 남은 1은 상대 학생 안의 Rc 몫입니다. 서로 상대가 먼저 정리되기를 기다리니 둘 다 0이 되지 않습니다(이 예에서는 프로그램이 끝날 때 운영체제가 메모리를 거둬 갑니다).

이런 누수는 컴파일 오류도 패닉도 아닙니다. Rust 는 해제된 메모리를 쓰는 일은 막지만, 모든 메모리가 반드시 해제된다고 약속하지는 않습니다.

5.2Weak<T>: 주인이 아닌 포인터

Weak<T> 는 Rc 의 값을 가리키지만 strong 수에 들어가지 않는 포인터입니다. Rc::downgrade(&rc) 로 만들면 weak 수가 1 오릅니다. 값은 strong 수가 0이 되면 weak 수와 상관없이 정리되므로, 쓸 때마다 upgrade() 로 Option<Rc<T>> 를 받아 확인합니다(살아 있으면 Some, 아니면 None).

src/bin/cycle_weak.rs
use std::cell::RefCell;
use std::rc::{Rc, Weak};

// 짝꿍은 약한 참조로만 가리킨다
struct Student {
    name: &'static str,
    buddy: RefCell<Weak<Student>>,
}

fn student(name: &'static str) -> Rc<Student> {
    Rc::new(Student { name, buddy: RefCell::new(Weak::new()) })
}

impl Drop for Student {
    fn drop(&mut self) {
        println!("  정리: {}", self.name);
    }
}

fn main() {
    let a = student("민지");
    let b = student("준호");
    *a.buddy.borrow_mut() = Rc::downgrade(&b);
    *b.buddy.borrow_mut() = Rc::downgrade(&a);
    println!("민지: strong {}, weak {}",
             Rc::strong_count(&a), Rc::weak_count(&a));

    if let Some(friend) = a.buddy.borrow().upgrade() {
        println!("민지의 짝꿍: {}", friend.name);
    }
    drop(b); // 준호가 먼저 떠난다
    match a.buddy.borrow().upgrade() {
        Some(f) => println!("아직 있음: {}", f.name),
        None => println!("민지의 짝꿍은 이제 없음"),
    }
    println!("main 끝");
}
$ cargo run --bin cycle_weak
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/cycle_weak`
민지: strong 1, weak 1
민지의 짝꿍: 준호
  정리: 준호
민지의 짝꿍은 이제 없음
main 끝
  정리: 민지

이번에는 두 학생이 모두 정리됩니다. drop(b) 로 준호의 strong 수가 0이 되자 바로 "정리: 준호"가 출력되고, 그 뒤 민지의 upgrade() 는 None 을 돌려줍니다. 민지는 main 끝에서 정리됩니다.

5.3나무 구조: 아래로는 Rc, 위로는 Weak

순환이 생기기 쉬운 대표적인 모양이 부모와 자식이 서로를 아는 나무 구조입니다. 상위 폴더가 하위 폴더를 소유하는 것은 자연스럽지만(상위를 지우면 하위도 지워짐), 하위가 상위를 살려 둘 이유는 없습니다. 그래서 아래 방향은 Rc, 위 방향은 Weak 로 둡니다.

src/bin/folder.rs
use std::cell::RefCell;
use std::rc::{Rc, Weak};

// 폴더는 하위 폴더를 소유하고(Rc), 상위 폴더는 빌려 본다(Weak)
struct Folder {
    name: String,
    parent: RefCell<Weak<Folder>>,
    children: RefCell<Vec<Rc<Folder>>>,
}

impl Folder {
    fn new(name: &str) -> Rc<Folder> {
        Rc::new(Folder {
            name: name.to_string(),
            parent: RefCell::new(Weak::new()),
            children: RefCell::new(Vec::new()),
        })
    }
}

fn add_child(parent: &Rc<Folder>, child: &Rc<Folder>) {
    *child.parent.borrow_mut() = Rc::downgrade(parent);
    parent.children.borrow_mut().push(Rc::clone(child));
}

// 위로 올라가며 전체 경로를 만든다
fn path(f: &Rc<Folder>) -> String {
    match f.parent.borrow().upgrade() {
        Some(p) => format!("{}/{}", path(&p), f.name),
        None => f.name.clone(),
    }
}

fn main() {
    let home = Folder::new("home");
    let docs = Folder::new("문서");
    let hw = Folder::new("숙제");
    add_child(&home, &docs);
    add_child(&docs, &hw);

    println!("{}", path(&hw));
    println!("home 의 하위: {}개", home.children.borrow().len());
    println!("문서: strong {}, weak {}",
             Rc::strong_count(&docs), Rc::weak_count(&docs));
}
$ cargo run --bin folder
   Compiling ptr v0.1.0 (…/p8/ptr)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/folder`
home/문서/숙제
home 의 하위: 1개
문서: strong 2, weak 1

문서 폴더의 strong 수 2는 변수 docs 와 home 의 자식 목록, weak 수 1은 숙제 의 parent 입니다. path 는 upgrade 로 부모를 얻어 위로 올라가다가 None(최상위)에서 멈춥니다.

home 문서 숙제 실선: children 의 Rc (소유) 점선: parent 의 Weak (소유하지 않음) 고리 안에 Weak 가 하나라도 있으면 strong 수가 0이 될 수 있다
그림 4. 폴더 나무. 소유는 위에서 아래로만 흐르므로 순환이 생기지 않는다.

5.4어떤 포인터를 고를까

상황쓸 것규칙 검사
잠깐 빌려 보기&T, &mut T컴파일 중 (수명)
값을 힙에 두고 혼자 소유, 재귀 타입, 트레이트 객체Box<T>컴파일 중
한 스레드 안에서 주인 여럿, 읽기만Rc<T>컴파일 중 (불변만 허용)
불변 참조만 있는데 안을 고쳐야 함RefCell<T>실행 중 (어기면 패닉)
주인 여럿이 함께 고침Rc<RefCell<T>>실행 중
가리키되 살려 두지 않음 (부모, 짝꿍, 캐시)Weak<T>upgrade 로 매번 확인
핵심 정리
  • Rc 끼리 고리를 이루면 strong 수가 0이 되지 않아 누수가 생깁니다. 이것은 컴파일 오류가 아닙니다.
  • Weak 는 strong 수에 들어가지 않는 포인터입니다. Rc::downgrade 로 만들고 upgrade() 로 Option<Rc<T>> 를 받아 씁니다.
  • 나무 구조는 아래 방향 Rc, 위 방향 Weak 로 둡니다.

5.5연습문제

1. 다음 시그니처의 함수를 완성하세요. text 에서 sep 가 처음 나오는 곳 뒤의 부분을 돌려주고, 없으면 빈 문자열을 돌려줍니다. sep 로 넘긴 String 이 먼저 사라져도 결과를 쓸 수 있어야 합니다. fn after(text: &str, sep: &str) -> &str 에 수명을 알맞게 붙이세요.

풀이 보기

결과는 text 에서만 나오므로 text 와 반환만 'a 로 묶습니다. 둘 다 묶으면 at 이 블록 안에서 사라질 때 E0597 이 납니다.

src/bin/ex1_after.rs
// sep 뒤의 부분을 돌려준다. 없으면 빈 문자열.
fn after<'a>(text: &'a str, sep: &str) -> &'a str {
    match text.find(sep) {
        Some(i) => &text[i + sep.len()..],
        None => "",
    }
}

fn main() {
    let mail = String::from("minji@example.com");
    let domain;
    {
        let at = String::from("@");
        domain = after(&mail, &at);
    }
    println!("도메인: {domain}");
    println!("없을 때: [{}]", after("abc", "#"));
}
$ cargo run --bin ex1_after
   Compiling ex v0.1.0 (…/p8/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex1_after`
도메인: example.com
없을 때: []

2. 시 전체(&str)를 받아 어떤 낱말이 들어 있는 행만 골라 Vec<Line> 로 돌려주세요. Line 은 행 번호와 그 행의 참조를 담는 구조체입니다.

풀이 보기

Line<'a> 의 'a 를 시 전체의 수명과 묶어야 하므로 find_lines 의 반환 타입에 Vec<Line<'a>> 를 적습니다. word 는 결과와 관계없습니다.

src/bin/ex2_lines.rs
// 시의 한 줄을 가리키는 구조체
struct Line<'a> {
    no: usize,
    text: &'a str,
}

fn find_lines<'a>(poem: &'a str, word: &str) -> Vec<Line<'a>> {
    let mut found = Vec::new();
    let mut no = 0;
    for text in poem.lines() {
        no += 1;
        if text.contains(word) {
            found.push(Line { no, text });
        }
    }
    found
}

fn main() {
    let poem = String::from(
        "죽는 날까지 하늘을 우러러\n\
         한 점 부끄럼이 없기를\n\
         잎새에 이는 바람에도\n\
         나는 괴로워했다",
    );
    for line in find_lines(&poem, "는") {
        println!("{}행: {}", line.no, line.text);
    }
}
$ cargo run --bin ex2_lines
   Compiling ex v0.1.0 (…/p8/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex2_lines`
1행: 죽는 날까지 하늘을 우러러
3행: 잎새에 이는 바람에도
4행: 나는 괴로워했다

3. 3.2절의 Expr 에 뺄셈 Sub 와 부호 바꾸기 Neg(식 하나를 받음)를 더하고, -(10 - 4) + 1 을 계산하세요.

풀이 보기

Neg 는 상자 하나만 담는 변형입니다. 결과는 -5 입니다.

src/bin/ex3_neg.rs
enum Expr {
    Num(i64),
    Add(Box<Expr>, Box<Expr>),
    Sub(Box<Expr>, Box<Expr>),
    Neg(Box<Expr>),
}

fn eval(e: &Expr) -> i64 {
    match e {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => eval(a) + eval(b),
        Expr::Sub(a, b) => eval(a) - eval(b),
        Expr::Neg(a) => -eval(a),
    }
}

fn main() {
    // -(10 - 4) + 1
    let e = Expr::Add(
        Box::new(Expr::Neg(Box::new(Expr::Sub(
            Box::new(Expr::Num(10)),
            Box::new(Expr::Num(4)),
        )))),
        Box::new(Expr::Num(1)),
    );
    println!("결과: {}", eval(&e));
}
$ cargo run --bin ex3_neg
   Compiling ex v0.1.0 (…/p8/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex3_neg`
결과: -5

4. 다음 프로그램의 출력을 실행하기 전에 예측하세요. "공용"과 "혼자"는 각각 언제 정리될까요?

use std::rc::Rc;

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("정리: {}", self.0);
    }
}

fn main() {
    let x = Rc::new(Noisy("공용"));
    let _solo = Noisy("혼자");
    let y = Rc::clone(&x);
    drop(x);
    println!("x 버림, 남은 주인 {}명", Rc::strong_count(&y));
    drop(y);
    println!("main 끝");
}
풀이 보기

drop(x) 는 Rc 하나만 버리므로 수가 1로 줄 뿐 "공용"은 아직 정리되지 않습니다. drop(y) 에서 수가 0이 되어 그때 정리됩니다. "혼자"는 main 이 끝날 때 정리됩니다.

$ cargo run --bin ex4_predict
   Compiling ex v0.1.0 (…/p8/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex4_predict`
x 버림, 남은 주인 1명
정리: 공용
main 끝
정리: 혼자

5. 동아리(Team)는 부원 목록을 Rc<Member> 로 소유하고, 부원은 자기 동아리를 Weak<Team> 으로 기억하게 만드세요. 부원의 동아리 이름을 출력하고, 동아리가 사라진 뒤에는 "(해체됨)"을 출력해야 합니다.

풀이 보기

동아리가 정리되면 부원 목록도 정리되므로 하린의 strong 수가 2에서 1로 줄어드는 것도 확인할 수 있습니다.

src/bin/ex5_team.rs
use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Team {
    name: String,
    members: RefCell<Vec<Rc<Member>>>,
}

struct Member {
    name: String,
    team: RefCell<Weak<Team>>,
}

fn join(team: &Rc<Team>, name: &str) -> Rc<Member> {
    let m = Rc::new(Member {
        name: name.to_string(),
        team: RefCell::new(Rc::downgrade(team)),
    });
    team.members.borrow_mut().push(Rc::clone(&m));
    m
}

fn team_of(m: &Member) -> String {
    match m.team.borrow().upgrade() {
        Some(t) => t.name.clone(),
        None => String::from("(해체됨)"),
    }
}

fn main() {
    let team = Rc::new(Team {
        name: String::from("과학 동아리"),
        members: RefCell::new(Vec::new()),
    });
    let a = join(&team, "하린");
    let b = join(&team, "도윤");
    println!("{}: {}, 인원 {}명", a.name, team_of(&a),
             team.members.borrow().len());
    drop(team);
    println!("{}: {}", b.name, team_of(&b));
    println!("하린 주인 {}명", Rc::strong_count(&a));
}
$ cargo run --bin ex5_team
   Compiling ex v0.1.0 (…/p8/ex)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in …
     Running `target/debug/ex5_team`
하린: 과학 동아리, 인원 2명
도윤: (해체됨)
하린 주인 1명
참고 공식 책 15.6절 Reference Cycles Can Leak Memory · std 문서 std::rc::Weak, Rc::downgrade, Weak::upgrade