0Pricing
Learn Rust Coding · 강의

스레드로 데이터 이동하기

move 클로저를 올바르게 사용해 보세요.

스레드로 데이터 이동하기은(는) CoddyKit의 무료 Learn Rust Coding 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Learn Rust Coding 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Closures Capture the Environment

A closure passed to thread::spawn can use variables from the surrounding scope. By default Rust borrows them.

But a spawned thread might outlive the function that created it, so a plain borrow is not safe. Rust rejects this at compile time.

The Borrow Problem

If a thread borrows a local variable, the compiler cannot prove the variable lives long enough. The thread could keep running after the variable is dropped.

The code below does not compile, because the closure only borrows data.

use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    // ERROR: closure may outlive `data`
    let h = thread::spawn(|| {
        println!("{:?}", data);
    });
    h.join().unwrap();
}

The move Keyword

Adding move before the closure forces it to take ownership of the captured variables. They are moved into the thread.

Now the thread owns the data, so it is guaranteed to stay valid for the thread's lifetime.

use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    let h = thread::spawn(move || {
        println!("{:?}", data);
    });
    h.join().unwrap();
}

Ownership Transfers Out

Once a value is moved into a thread, the original scope can no longer use it. Ownership has moved away.

Trying to use data in main after the move would be a compile error. The thread is now the sole owner.

use std::thread;

fn main() {
    let data = vec![1, 2, 3];
    let h = thread::spawn(move || println!("{:?}", data));
    // println!("{:?}", data); // ERROR: value moved
    h.join().unwrap();
}

Moving Copy Types

Types that implement Copy, like integers, are copied rather than moved. The closure gets its own copy.

So after a move closure captures a number, you can still use the original in main.

use std::thread;

fn main() {
    let n = 42;
    let h = thread::spawn(move || {
        println!("thread sees {}", n);
    });
    println!("main still sees {}", n);
    h.join().unwrap();
}

Send: Safe to Transfer

A type can only be moved into another thread if it implements the Send trait. Send means it is safe to transfer ownership across threads.

Most types are Send automatically. A few, like Rc, are not, and the compiler will reject moving them.

Rc Is Not Send

Rc is a single-threaded reference counter. Its count is not protected against concurrent updates, so it is not Send.

Trying to move an Rc into a thread fails to compile. You will use Arc instead in the next lesson.

use std::rc::Rc;
use std::thread;

fn main() {
    let r = Rc::new(5);
    // ERROR: `Rc<i32>` cannot be sent between threads safely
    let h = thread::spawn(move || println!("{}", r));
    h.join().unwrap();
}

Moving Multiple Values

A single move closure can capture several variables at once. All of them are moved into the thread.

This is handy when a worker needs both some input and a label.

use std::thread;

fn main() {
    let label = String::from("sum");
    let nums = vec![1, 2, 3, 4];
    let h = thread::spawn(move || {
        let total: i32 = nums.iter().sum();
        println!("{} = {}", label, total);
    });
    h.join().unwrap();
}

Cloning Before Moving

If both the thread and the main function need a value, clone it first. Give one clone to the thread and keep the other.

Cloning copies the data, so each side owns an independent value.

use std::thread;

fn main() {
    let original = String::from("hello");
    let for_thread = original.clone();
    let h = thread::spawn(move || println!("thread: {}", for_thread));
    println!("main: {}", original);
    h.join().unwrap();
}

Returning Moved Data Back

A thread that owns moved data can return it, handing ownership back to the parent through join.

This pattern moves data in, processes it, then moves the result out.

use std::thread;

fn main() {
    let mut v = vec![3, 1, 2];
    let h = thread::spawn(move || {
        v.sort();
        v
    });
    let sorted = h.join().unwrap();
    println!("{:?}", sorted);
}

Why move Is Required

Without move, the borrow checker assumes the closure borrows. Because spawned threads have no fixed lifetime bound to the caller, borrows are unsafe.

The move keyword converts borrows into ownership transfers, satisfying the 'static requirement of spawn.

Quick Check

Test your understanding of moving data into threads.

Recap

You learned that thread closures must own the data they use, achieved with the move keyword.

Moving transfers ownership, while Copy types are copied. The Send trait marks what is safe to transfer, and Rc is not Send.

Next you will share data between threads using Arc and Mutex.

자주 묻는 질문

“스레드로 데이터 이동하기” 강의는 무료인가요?

네 — “스레드로 데이터 이동하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Learn Rust Coding 강의 전체를 잠금 해제할 수 있습니다. Learn Rust Coding 강의에는 총 4개의 강의가 포함되어 있습니다.

“스레드로 데이터 이동하기”에서 뭘 배우나요?

move 클로저를 올바르게 사용해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Learn Rust Coding을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Learn Rust Coding을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Learn Rust Coding은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“스레드로 데이터 이동하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Learn Rust Coding 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Learn Rust Coding 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 스레드 생성하기
  2. 스레드로 데이터 이동하기
  3. Arc와 Mutex로 공유하기
  4. 결과 결합하고 수집하기
← Learn Rust Coding(으)로 돌아가기