rust 中的 move 关键字

453 阅读1分钟

在 rust 编程中, closure, 新开启线程,新的 features 等场景都会使用一些 move 关键字

move 主要是复制整个栈上的数据,复制堆上数据的引用, 并且 当类型实现Copy特征时,不会转移所有权,而是直接对值进行拷贝

#[allow(unused)]
use std::fmt::Debug;
use std::thread;

// 用于演示 move 关键字
struct Hello {
    i_ad: i64, // 分配在栈上
    v_ad: Vec<String>, // 胖指针, buff 字段的数据保存在堆中
}

fn main() {
    let h = Hello { i_ad: 233i64, v_ad: vec!["".to_owned()] };

    println!("线程 id {:?}                     &h         {:?}", thread::current().id().to_owned(), &h as *const _); 
    println!("线程 id {:?} i_ad 字段           &h.i_ad    {:?}", thread::current().id().to_owned(), &h.i_ad as *const _);
    println!("线程 id {:?} v_ad 字段           &h.v_ad    {:?}", thread::current().id().to_owned(), &h.v_ad as *const _);
    println!("线程 id {:?} v_ad 字段的第一个数据 &h.v_ad[0] {:?}", thread::current().id().to_owned(), &h.v_ad[0] as *const _);
    println!("======================================================================================");

    // 在子线程中运行
    let v = thread::spawn(move || {
        println!("线程 id {:?}                     &h         {:?}", thread::current().id().to_owned(), &h as *const _); // 将 h 复制到了新的线程栈
        println!("线程 id {:?} i_ad 字段           &h.i_ad    {:?}", thread::current().id().to_owned(), &h.i_ad as *const _); // 将 Hello  上的字段复制到了新的线程栈
        println!("线程 id {:?} v_ad 字段           &h.v_ad    {:?}", thread::current().id().to_owned(), &h.v_ad as *const _);
        println!("线程 id {:?} v_ad 字段的第一个数据 &h.v_ad[0] {:?}", thread::current().id().to_owned(), &h.v_ad[0] as *const _); // 在堆上的数据保持
        return ();
    }).join().unwrap();
    // move 只会拷贝 栈上的数据,不会拷贝堆上的数据
}

参考

  1. [Rust所有权转移时发生了奇怪的深拷贝](course.rs/profiling/p…)