代碼在此git
// 編譯成功
fn main() {
let num = 1;
let num = 2;
println!("num: {}", num);
}
複製代碼
編譯失敗github
fn main() {
let num = 1;
num = 2;
println!("num: {}", num);
}
複製代碼
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`.
複製代碼
// 編譯成功
fn main() {
let mut num = 1;
num = 2;
println!("num: {}", num);
}
複製代碼
// 編譯成功
fn main() {
// let s1 = Box::new("word");
let s1 = String::from("word");
println!("s1: {}", s1);
}
複製代碼
編譯失敗bash
fn main() {
// let s1 = Box::new("word");
let s1 = String::from("word");
let s2 = s1;
println!("s1: {}", s1);
}
複製代碼
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 | let s2 = 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`.
複製代碼
// 編譯成功
#[derive(Debug)]
struct Gps {
x: i32,
y: i32,
}
fn main() {
let a = Gps { x: 3, y: 7 };
println!("a struct: {:#?}", a);
}
複製代碼
// 編譯失敗
#[derive(Debug)]
struct Gps {
x: i32,
y: i32,
}
fn main() {
let a = Gps { x: 3, y: 7 };
let b = a;
println!("a struct: {:#?}", a);
}
複製代碼
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 | let b = 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`.
複製代碼
// 編譯成功
#[derive(Debug, Copy, Clone)]
struct Gps {
x: i32,
y: i32,
}
fn main() {
let a = Gps { x: 3, y: 7 };
let b = a;
println!("a struct: {:#?}", a);
}
複製代碼