AmitKumarDas / Decisions

Apache License 2.0
10 stars 3 forks source link

Rust: copy vs. non-copy #135

Open AmitKumarDas opened 5 years ago

AmitKumarDas commented 5 years ago

:nerd_face: Primitives are stored in a stack and fall under copy category :nerd_face: Memory / types stored in a heap and are non-copy category :nerd_face: Box has non-copy semantics :nerd_face: vec![1,2,3,] has non-copy semantics

:nerd_face: copy type movement leave the original untouched :green_apple: :nerd_face: A non-copy type must move :apple:

    // A non-copy type.
    let movable = Box::new(3);

    // `mem::drop` requires `T` so this must take by value. A copy type
    // would copy into the closure leaving the original untouched.
    // A non-copy must move and so `movable` immediately moves into
    // the closure.
    let consume = || {
        println!("`movable`: {:?}", movable);
        mem::drop(movable);
    };

    // `consume` consumes the variable so this can only be called once.
    consume();
    //consume();
    // ^ TODO: Try uncommenting this line.
let greeting = "hello";

// A non-copy type.
// `to_owned` creates owned data from borrowed one
let mut farewell = "goodbye".to_owned();