Rust 에서 let b = a; 는 기본적으로 소유권을 이동(move)한다. 이동한 뒤에는 a 를 쓸 수 없다. 정수처럼 Copy 를 구현한 타입만 비트 복사로 원본을 남기고, 힙 데이터까지 복제하려면 clone() 을 직접 호출해야 한다.

Java 나 Python 에서 대입은 객체를 가리키는 참조를 복사하고, 두 변수가 같은 객체를 함께 가리킨다. Rust 는 같은 대입 문법에서 원본 변수를 무효로 만든다. 이 차이가 컴파일 에러로 어떻게 드러나는지, 어떤 타입이 복사되고 어떤 타입이 이동하는지 정리하고 싶었다. 아래 예제는 모두 rustc 1.94.1, edition 2021 에서 컴파일했고, 컴파일되는 예제는 실행해 출력을 확인했다.

이동

String 을 다른 변수에 대입한 뒤 원래 변수를 쓰면 컴파일되지 않는다.

fn main() {
    let original = String::from("hello");
    let moved = original;
    println!("{moved}");
    println!("{original}");
}
error[E0382]: borrow of moved value: `original`
 --> move_assign.rs:5:16
  |
2 |     let original = String::from("hello");
  |         -------- move occurs because `original` has type `String`, which does not implement the `Copy` trait
3 |     let moved = original;
  |                 -------- value moved here
4 |     println!("{moved}");
5 |     println!("{original}");
  |                ^^^^^^^^ value borrowed here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let moved = original.clone();
  |                         ++++++++

에러 메시지가 원인을 그대로 적는다. String 은 Copy 를 구현하지 않으므로 3행에서 값이 moved 로 이동했고, 5행은 이동한 뒤의 값을 사용한다. 메시지의 borrow 는 println! 이 값을 참조로 읽기 때문에 나온 표현이다.

이동할 때 메모리에서 일어나는 일을 확인해 봤다. 이동 전후의 힙 주소를 비교하고, String 자체의 크기를 출력했다.

fn main() {
    let original = String::from("hello");
    let heap_before = original.as_ptr();
    let moved = original;
    println!("same heap buffer: {}", heap_before == moved.as_ptr());
    println!("size_of::<String>() = {}", std::mem::size_of::<String>());

    let cloned = moved.clone();
    println!("clone shares buffer: {}", moved.as_ptr() == cloned.as_ptr());
}
same heap buffer: true
size_of::<String>() = 24
clone shares buffer: false
move 와 clone 의 메모리 — move 는 스택의 24바이트만 복사하고, clone 은 힙 버퍼를 새로 할당한다let moved = original;스택힙originalptrlen 5cap 5무효 (이동됨)movedptrlen 5cap 5hello같은 버퍼let cloned = moved.clone();movedptrlen 5cap 5helloclonedptrlen 5cap 5hello새 버퍼 할당

String 값은 힙 버퍼를 가리키는 포인터, 길이, 용량으로 구성된다. 64비트 환경에서 24바이트다. 이동하면 이 24바이트가 새 변수의 값이 되고, 힙의 문자열은 그대로 남는다. 이동 후 moved 가 가리키는 힙 주소가 이동 전과 같은 이유다. Copy 문서는 복사와 이동 모두 메모리에서는 비트 복사일 수 있고, 차이는 대입 후에 원본을 쓸 수 있는지뿐이라고 설명한다.

원본을 무효로 만드는 이유는 drop 에 있다. 두 변수가 같은 힙 버퍼를 가리킨 채 둘 다 스코프 끝에서 drop 되면 같은 버퍼가 두 번 해제된다. 이동으로 소유자를 하나로 유지하면 drop 도 한 번만 실행된다.

함수 인자와 반환

함수 인자로 값을 넘기는 것도 대입과 같은 이동이다.

fn consume(text: String) {
    println!("consume {text}");
}

fn main() {
    let message = String::from("hello");
    consume(message);
    println!("{message}");
}
error[E0382]: borrow of moved value: `message`
 --> move_fn.rs:8:16
  |
6 |     let message = String::from("hello");
  |         ------- move occurs because `message` has type `String`, which does not implement the `Copy` trait
7 |     consume(message);
  |             ------- value moved here
8 |     println!("{message}");
  |                ^^^^^^^ value borrowed here after move
  |
note: consider changing this parameter type in function `consume` to borrow instead if owning the value isn't necessary
 --> move_fn.rs:1:18
  |
1 | fn consume(text: String) {
  |    -------       ^^^^^^ this parameter takes ownership of the value
  |    |
  |    in this function
help: consider cloning the value if the performance cost is acceptable
  |
7 |     consume(message.clone());
  |                    ++++++++

소유권이 consume 의 매개변수 text 로 넘어갔고, text 의 스코프가 끝나는 consume 끝에서 문자열이 drop 된다. 호출한 쪽에는 더 이상 값이 없다.

반복문 안에서 이동하면 두 번째 반복에서 같은 에러가 난다. 컴파일러는 앞선 반복에서 이미 이동했다고 표시한다.

// consume 은 위와 같다
fn main() {
    let message = String::from("hello");
    for _ in 0..2 {
        consume(message);
    }
}
error[E0382]: use of moved value: `message`
 --> loop_move.rs:8:17
  |
6 |     let message = String::from("hello");
  |         ------- move occurs because `message` has type `String`, which does not implement the `Copy` trait
7 |     for _ in 0..2 {
  |     ------------- inside of this loop
8 |         consume(message);
  |                 ^^^^^^^ value moved here, in previous iteration of loop

함수가 값을 반환하면 소유권이 호출한 쪽으로 돌아온다. 값을 받아서 고친 뒤 다시 돌려주는 함수는 이렇게 쓸 수 있다.

fn append_suffix(mut text: String) -> String {
    text.push_str(" world");
    text
}

fn main() {
    let message = String::from("hello");
    let message = append_suffix(message);
    println!("{message}");
}
hello world

값을 쓸 때마다 넘겼다가 돌려받는 방식은 반환값이 늘어날수록 번거롭다고 봤다. 위 에러의 note 가 제안하듯, 소유권이 필요 없는 함수는 매개변수를 참조로 바꾼다. 참조와 borrow 는 시리즈의 다음 글에서 다룬다.

부분 이동

struct 의 필드 하나만 이동할 수도 있다. 이동하지 않은 필드는 계속 쓸 수 있지만, struct 전체는 쓸 수 없다.

struct User {
    name: String,
    age: u32,
}

fn main() {
    let user = User { name: String::from("alice"), age: 30 };
    let name = user.name;
    println!("{name} {}", user.age);
    let _whole = user;
}
error[E0382]: use of partially moved value: `user`
  --> partial.rs:10:18
   |
 8 |     let name = user.name;
   |                --------- value partially moved here
 9 |     println!("{name} {}", user.age);
10 |     let _whole = user;
   |                  ^^^^ value used here after partial move
   |
   = note: partial move occurs because `user.name` has type `String`, which does not implement the `Copy` trait

9행의 user.age 는 통과했다. age 는 이동하지 않았기 때문이다. 10행은 name 이 빠진 user 전체를 이동하려 하므로 거부된다.

패턴 매칭도 값을 바인딩하면서 이동한다. if let Some(name) 은 Option 안의 String 을 name 으로 이동한다.

fn main() {
    let nickname: Option<String> = Some(String::from("ally"));
    if let Some(name) = nickname {
        println!("hi {name}");
    }
    println!("{nickname:?}");
}
error[E0382]: borrow of partially moved value: `nickname`
 --> match_move.rs:6:16
  |
3 |     if let Some(name) = nickname {
  |                 ---- value partially moved here
...
6 |     println!("{nickname:?}");
  |                ^^^^^^^^ value borrowed here after partial move
  |
  = note: partial move occurs because value has type `String`, which does not implement the `Copy` trait
help: borrow this binding in the pattern to avoid moving the value
  |
3 |     if let Some(ref name) = nickname {
  |                 +++

Drop 을 구현한 struct 에서는 필드를 이동할 수 없다.

struct Session {
    token: String,
}

impl Drop for Session {
    fn drop(&mut self) {
        println!("drop session");
    }
}

fn main() {
    let session = Session { token: String::from("abc") };
    let token = session.token;
    println!("{token}");
}
error[E0509]: cannot move out of type `Session`, which implements the `Drop` trait
  --> partial_drop.rs:13:17
   |
13 |     let token = session.token;
   |                 ^^^^^^^^^^^^^
   |                 |
   |                 cannot move out of here
   |                 move occurs because `session.token` has type `String`, which does not implement the `Copy` trait

session 이 스코프를 벗어나면 drop 메서드가 실행되고, 이 메서드는 필드를 사용할 수 있다. rustc --explain E0509 는 필드가 이동한 struct 에서는 drop 을 실행할 수 없다고 설명한다. 그래서 Drop 을 구현한 타입은 필드를 이동할 수 없는 하나의 단위로 다뤄진다. The Rust Reference 도 이동할 수 있는 필드를 Drop 을 구현하지 않은 타입의 필드로 한정한다.

Copy

정수는 대입해도 원본을 계속 쓸 수 있다.

fn main() {
    let count = 5;
    let copied = count;
    println!("{count} {copied}");
}
5 5

i32 가 Copy 를 구현하기 때문이다. Copy 타입은 대입이나 인자 전달에서 비트 복사되고, 원본도 유효하게 남는다. 정수, 부동소수점, bool, char, 공유 참조 &T 가 Copy 이고, 원소가 모두 Copy 인 튜플과 배열도 Copy 다.

직접 만든 타입은 #[derive(Clone, Copy)] 로 Copy 를 붙인다. Clone 이 Copy 의 상위 trait(supertrait)이라서 둘을 함께 적어야 한다.

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

fn shift(mut point: Point) -> Point {
    point.x += 1;
    point.y += 1;
    point
}

fn main() {
    let origin = Point { x: 0, y: 0 };
    let shifted = shift(origin);
    println!("{origin:?} {shifted:?}");
}
Point { x: 0, y: 0 } Point { x: 1, y: 1 }

shift 는 복사본을 받아 고쳤고, origin 은 호출 뒤에도 그대로다.

Copy 를 구현하려면 모든 필드가 Copy 여야 한다. String 필드가 있는 struct 에 Copy 를 붙이면 E0204 가 발생한다.

#[derive(Clone, Copy)]
struct Account {
    id: u64,
    owner: String,
}
error[E0204]: the trait `Copy` cannot be implemented for this type
 --> copy_e0204.rs:1:17
  |
1 | #[derive(Clone, Copy)]
  |                 ^^^^
...
4 |     owner: String,
  |     ------------- this field does not implement `Copy`

필드가 모두 Copy 여도 Drop 을 구현한 타입이면 E0184 가 발생한다.

#[derive(Clone, Copy)]
struct Handle {
    id: u32,
}

impl Drop for Handle {
    fn drop(&mut self) {
        println!("drop {}", self.id);
    }
}
error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor
 --> copy_drop.rs:1:17
  |
1 | #[derive(Clone, Copy)]
  |                 ^^^^ `Copy` not allowed on types with destructors

Copy 문서는 String 을 예로 든다. String 을 비트 복사하면 힙 버퍼는 그대로 두고 포인터, 길이, 용량만 복사된다. 두 값이 같은 버퍼의 해제를 각자 맡게 되어 버퍼가 두 번 해제된다. 문서는 이를 일반화해, Drop 을 구현한 타입은 자기 크기(size_of::<T>) 바이트에 담기지 않는 자원을 관리하므로 Copy 가 될 수 없다고 설명한다. 가변 참조 &mut T 도 Copy 가 아니다. 복사하면 같은 값을 가리키는 가변 참조가 둘 생긴다.

Copy 의 동작은 재정의할 수 없고, 항상 비트 복사다. 문서는 Copy 를 붙일 수 있는 타입이면 붙이라고 권하면서도, Copy 가 타입의 공개 API 에 포함된다는 점을 함께 적는다. 나중에 String 같은 필드를 추가하면 Copy 구현을 제거해야 하고, 대입 뒤에 원본을 쓰던 호출부가 모두 컴파일 에러가 된다. 앞으로 필드가 바뀔 수 있는 타입이라면 처음부터 Copy 를 붙이지 않는 편이 낫다고 봤다.

Clone

clone() 은 값을 명시적으로 복제한다. String 이나 Vec 의 clone 은 새 힙 버퍼를 할당하고 내용을 복사한다. 앞의 예제에서 clone shares buffer: false 가 출력된 이유다. Vec<String> 이면 바깥 버퍼에 더해 원소 String 마다 버퍼를 새로 할당한다.

Clone 문서는 두 trait 의 차이를 이렇게 정리한다. Copy 는 암묵적이고 비용이 낮은 비트 복사다. Clone 은 항상 명시적으로 호출하고, 비용은 타입에 따라 다르다. clone 메서드는 임의의 코드를 실행할 수 있다.

복제된 값은 원본과 소유자가 다르므로 drop 도 따로 실행된다. 이름을 출력하는 Drop 을 붙여 확인했다.

#[derive(Clone)]
struct Buffer {
    name: String,
}

impl Drop for Buffer {
    fn drop(&mut self) {
        println!("drop {}", self.name);
    }
}

fn main() {
    let first = Buffer { name: String::from("first") };
    let moved = first;
    let mut cloned = moved.clone();
    cloned.name.push_str("-clone");
    println!("end of main");
}
end of main
drop first-clone
drop first

first 에서 moved 로 이동한 값은 한 번만 drop 됐고, 복제본은 따로 한 번 drop 됐다. Clone 은 Drop 과 함께 구현할 수 있다. 복제본이 자기 자원을 따로 가지므로 해제가 겹치지 않는다.

앞의 String 대입과 함수 인자 에러는 .clone() 을 붙이라고 제안했다. 원본과 복제본이 각자 바뀌어야 하면 clone 이 맞는 선택이다. 그런데 값을 읽기만 하는데 에러를 없애려고 clone 을 붙이면, 호출할 때마다 할당과 복사가 생긴다. 반복문이나 요청마다 실행되는 경로라면 그 비용이 쌓인다. 컴파일러가 제안하는 문구도 “성능 비용을 감수할 수 있다면” 이다. 이런 경우에는 함수 인자 에러의 note 처럼 참조로 넘기는 쪽을 먼저 검토하는 편이 낫다고 판단했다. clone() 이 코드에 보이므로, 어디서 복제 비용이 생기는지 코드 리뷰에서 찾을 수 있다.

마무리

이동은 원본 변수를 무효로 만들어 소유자를 하나로 유지하고, drop 이 한 번만 실행되게 한다. Copy 타입은 원본을 남기지만, 해제할 자원이 없는 타입만 Copy 가 될 수 있다. 힙 데이터의 복제는 clone() 호출로만 일어나므로, 복제 비용이 생기는 위치가 코드에 드러난다. 대입이 참조를 복사해 객체를 공유하는 Java·Python 과 달리, Rust 에서는 대입 한 줄의 의미를 타입이 정한다.

참고