The code in this

Immutable immutable

// Compilation succeeded
fn main() {
    let num = 1;
    let num = 2;
    println!("num: {}", num);
}
Copy the code

Compilation fails

fn main() {
    let num = 1;
    num = 2;
    println!("num: {}", num);
}
Copy the code
error[E0384]: cannot assign twice to immutable variable `num`
30 |     let num = 1;
   |         ---
   |         |
   |         first assignment to `num`
   |         help: make this binding mutable: `mut num`
31 |     num = 2;
   |     ^^^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error
For more information about this error, try `rustc --explain E0384`.
Copy the code
// Fn was successfully compiledmain() {
    letmut num = 1; num = 2; println! ("num: {}", num);
}
Copy the code

Transfer of ownership

// Fn was successfully compiledmain() {
    // let s1 = Box::new("word");
    let s1 = String::from("word"); println! ("s1: {}", s1);
}
Copy the code

Compilation fails

fn main() {
    // let s1 = Box::new("word");
    let s1 = String::from("word");
    lets2 = s1; println! ("s1: {}", s1);
}
Copy the code
error[E0382]: borrow of moved value: `s1`
25 |     let s1 = String::from("word");
   |         -- move occurs because `s1` has type `std::string::String`, which does not implement the `Copy` trait
26 |     lets2 = s1; | -- value moved here 27 | 28 | println! ("s1: {}", s1);
   |                        ^^ value borrowed here after move

error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
Copy the code

struct

// Compilation succeeded#[derive(Debug)]
struct Gps {
    x: i32,
    y: i32,
}

fn main() {
    leta = Gps { x: 3, y: 7 }; println! ("a struct: {:#? }", a);
}
Copy the code
// Failed to compile#[derive(Debug)]
struct Gps {
    x: i32,
    y: i32,
}

fn main() {
    let a = Gps { x: 3, y: 7 };
    letb = a; println! ("a struct: {:#? }", a);
}
Copy the code
error[E0382]: borrow of moved value: `a`
9  |     let a = Gps { x: 3, y: 7 };
   |         - move occurs because `a` has type `Gps`, which does not implement the `Copy` trait
10 |     letb = a; | - value moved here 11 | println! ("a struct: {:#? }", a);
   |                                 ^ value borrowed here after move

error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
Copy the code
// Compilation succeeded#[derive(Debug, Copy, Clone)]
struct Gps {
    x: i32,
    y: i32,
}

fn main() {
    let a = Gps { x: 3, y: 7 };
    letb = a; println! ("a struct: {:#? }", a);
}
Copy the code