0Pricing
Learn Rust Coding · Ders

Verileri İş Parçacıklarına Taşıma

move kapanışlarını doğru kullanın.

Verileri İş Parçacıklarına Taşıma, CoddyKit'te ücretsiz bir Learn Rust Coding dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Learn Rust Coding öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Learn Rust Coding kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“Verileri İş Parçacıklarına Taşıma” dersi ücretsiz mi?

Evet — “Verileri İş Parçacıklarına Taşıma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Learn Rust Coding kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Learn Rust Coding kursu toplamda 4 dersten oluşur.

“Verileri İş Parçacıklarına Taşıma” dersinde ne öğreneceğim?

move kapanışlarını doğru kullanın. Learn Rust Coding ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Learn Rust Coding öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Learn Rust Coding, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Verileri İş Parçacıklarına Taşıma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Learn Rust Coding dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Learn Rust Coding dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. İş Parçacıkları Oluşturma
  2. Verileri İş Parçacıklarına Taşıma
  3. Arc ve Mutex ile Paylaşma
  4. Birleştirme ve Sonuçları Toplama
← Learn Rust Coding Sayfasına Dön