1.Rust 中的每一個值都有一個叫做它的所有者(owner)的變量。
2.同時一次只能有一個所有者
3.當所有者變量離開作用域,這個值將被丟棄。
我們接下來會用代碼的形式來進行講解,不懂的可以去官方文檔看看語法。
{
let x = String::from("test");
println!("in scope hello this is {}", x);
}
println!("out scope hello this is {}", x);
當然,這段代碼是無法執行的,因爲根本無法通過編譯,報錯如下
error[E0425]: cannot find value `x` in this scope
--> src/main.rs:13:40
|
13 | println!("out scope hello this is {}", x);
| ^ not found in this scope
因爲x在爲這個String的值的所有者,在所有者離開作用域後值直接被釋放了,這一點和其它編程語言是很相似的。let x = String::from("123");
let y = x;
println!("x = {}, y = {}", x, y);
error[E0382]: use of moved value: `x`
--> src/main.rs:11:32
|
10 | let y = x;
| - value moved here
11 | println!("x = {}, y = {}", x, y);
| ^ value used here after move
|
= note: move occurs because `x` has type `std::string::String`, which does not implement the `Copy` trait
報錯上顯示x的值被移動了,你們可能在想,這是什麼鬼。我們接下來就來扯一下數據的內存吧
let x = 1;
let y = x;
println!("x = {}, y = {}", x, y);
fn hello(str: String)
{
println!("{}", str);
}
fn test()
{
let x = String::from("123");
hello(x);
println!("x = {}", x);
}
error[E0382]: use of moved value: `x`
--> src/main.rs:15:24
|
14 | hello(x);
| - value moved here
15 | println!("x = {}", x);
| ^ value used here after move
|
= note: move occurs because `x` has type `std::string::String`, which does not implement the `Copy` trait