移動、複製與 Clone

最後更新


把值交給另一個變數或函式時,Rust 預設「移動」所有權;只有 Copy 型別會自動複製,想要完整複製其他型別就明確呼叫 .clone()。

移動(move)


指派會移動所有權


Vec、String 這類型別在堆疊上只存「指標、長度、容量」,真正的資料在堆積(見 所有權)。let b = a 只複製了堆疊上那三個欄位,如果 a 和 b 都算擁有者,兩者離開作用域時會把同一塊堆積釋放兩次。Rust 的做法是:指派之後 a 失效,只有 b 是擁有者。
flowchart LR
    A["a(已失效)"] -.->|移動前| H["堆積:1, 2, 3"]
    B["b"] -->|移動後| H
  1. flowchart LR
  2. A["a(已失效)"] -.->|移動前| H["堆積:1, 2, 3"]
  3. B["b"] -->|移動後| H

下面這段無法編譯:a 的內容已經移給 b。
範例:
  1. fn main() {
  2. let a = vec![1, 2, 3];
  3. let b = a;
  4. println!("a 的長度:{}", a.len());
  5. println!("b = {:?}", b);
  6. }

輸出(編譯錯誤):
  1. error[E0382]: borrow of moved value: `a`
  2. --> main.rs:4:26
  3. |
  4. 2 | let a = vec![1, 2, 3];
  5. | - move occurs because `a` has type `Vec<i32>`, which does not implement the `Copy` trait
  6. 3 | let b = a;
  7. | - value moved here
  8. 4 | println!("a 的長度:{}", a.len());
  9. | ^ value borrowed here after move
  10. |
  11. help: consider cloning the value if the performance cost is acceptable
  12. |
  13. 3 | let b = a.clone();
  14. | ++++++++

會其他語言的讀者可以這樣對照:Python、JavaScript 的 b = a 讓兩個名字指向同一個物件;Rust 的 let b = a 則是把東西交出去,自己手上就沒了。

被移走的變數可以重新賦值


移動之後變數不能「讀」,但如果它是 mut,可以重新指派一個新值,之後就又能用了。
範例:
  1. fn main() {
  2. let mut s = String::from("第一份");
  3. let taken = s;
  4. s = String::from("第二份");
  5. println!("taken = {}", taken);
  6. println!("s = {}", s);
  7. }

輸出:
  1. taken = 第一份
  2. s = 第二份

for 迴圈會移動集合


for name in names 會把整個 Vec 交給迴圈,迴圈結束後 names 就不能用了。這段無法編譯:
範例:
  1. fn main() {
  2. let names = vec![String::from("Ann"), String::from("Bob")];
  3. for name in names {
  4. println!("哈囉 {}", name);
  5. }
  6. println!("共 {} 人", names.len());
  7. }

輸出(編譯錯誤):
  1. error[E0382]: borrow of moved value: `names`
  2. --> main.rs:6:24
  3. |
  4. 2 | let names = vec![String::from("Ann"), String::from("Bob")];
  5. | ----- move occurs because `names` has type `Vec<String>`, which does not implement the `Copy` trait
  6. 3 | for name in names {
  7. | ----- `names` moved due to this implicit call to `.into_iter()`
  8. ...
  9. 6 | println!("共 {} 人", names.len());
  10. | ^^^^^ value borrowed here after move
  11. |
  12. help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
  13. |
  14. 3 | for name in &names {
  15. | +

只是想讀取時,改成迭代參考 &names,所有權留在原處:
範例:
  1. fn main() {
  2. let names = vec![String::from("Ann"), String::from("Bob")];
  3. for name in &names {
  4. println!("哈囉 {}", name);
  5. }
  6. println!("共 {} 人", names.len());
  7. }

輸出:
  1. 哈囉 Ann
  2. 哈囉 Bob
  3. 共 2 人

更多迭代方式見 迭代器。

Copy 型別


哪些型別會自動複製


如果一個型別完全存放在堆疊上、複製成本極低,它可以實作 Copy 特徵(trait),指派時就直接複製一份,原變數照樣可用。常見的 Copy 型別:
類別例子
整數、浮點數i32、u8、usize、f64
布林與字元bool、char
元素都是 Copy 的元組與陣列(i32, char)、[f64; 3]
共享參考&T,例如 &str

String、Vec<T>、Box<T> 這類擁有堆積資料的型別都不是 Copy。
範例:
  1. fn main() {
  2. let x = 5;
  3. let y = x;
  4. let flag = true;
  5. let other = flag;
  6. let pair = (1, 'R');
  7. let pair2 = pair;
  8. let arr = [0.5_f64; 3];
  9. let arr2 = arr;
  10. let text: &str = "字面值";
  11. let text2 = text;
  12. println!("{} {} / {} {}", x, y, flag, other);
  13. println!("{:?} {:?}", pair, pair2);
  14. println!("{:?} {:?}", arr, arr2);
  15. println!("{} {}", text, text2);
  16. }

輸出:
  1. 5 5 / true true
  2. (1, 'R') (1, 'R')
  3. [0.5, 0.5, 0.5] [0.5, 0.5, 0.5]
  4. 字面值 字面值

讓自訂型別成為 Copy


所有欄位都是 Copy 時,可以用 #[derive(Clone, Copy)] 讓結構體也變成 Copy(Copy 要求同時實作 Clone)。複製出來的是獨立的一份,改 q 不影響 p。特徵本身的說明見 std::marker。
範例:
  1. #[derive(Clone, Copy)]
  2. struct Point {
  3. x: i32,
  4. y: i32,
  5. }
  6. fn main() {
  7. let p = Point { x: 1, y: 2 };
  8. let mut q = p;
  9. q.x = 10;
  10. println!("p = ({}, {})", p.x, p.y);
  11. println!("q = ({}, {})", q.x, q.y);
  12. }

輸出:
  1. p = (1, 2)
  2. q = (10, 2)

注意:只要有一個欄位不是 Copy,就不能 derive Copy。下面這段無法編譯,因為 String 擁有堆積資料:
範例:
  1. #[derive(Debug, Clone, Copy)]
  2. struct User {
  3. id: u32,
  4. name: String,
  5. }
  6. fn main() {
  7. let u = User { id: 1, name: String::from("Ann") };
  8. println!("{:?}", u);
  9. }

輸出(編譯錯誤):
  1. error[E0204]: the trait `Copy` cannot be implemented for this type
  2. --> main.rs:2:8
  3. |
  4. 1 | #[derive(Debug, Clone, Copy)]
  5. | ---- in this derive macro expansion
  6. 2 | struct User {
  7. | ^^^^
  8. 3 | id: u32,
  9. 4 | name: String,
  10. | ------------ this field does not implement `Copy`

修法是拿掉 Copy,只保留 Clone,需要複製時明確呼叫 .clone()。

Clone:明確的深複製


clone 複製整份資料


.clone() 會連同堆積上的資料一起複製,得到兩份完全獨立的值。修改複本不會影響原本的值。Clone 特徵見 std::clone。
範例:
  1. fn main() {
  2. let original = vec![String::from("a"), String::from("b")];
  3. let mut copy = original.clone();
  4. copy.push(String::from("c"));
  5. copy[0].push('!');
  6. println!("original = {:?}", original);
  7. println!("copy = {:?}", copy);
  8. }

輸出:
  1. original = ["a", "b"]
  2. copy = ["a!", "b", "c"]

Copy 和 Clone 的差別:
CopyClone
觸發方式指派、傳參數時自動發生必須寫 .clone()
成本只複製堆疊上的位元組,很便宜可能配置堆積並複製大量資料
適用小型、無堆積資料的型別幾乎所有型別

注意:.clone() 是最快讓編譯錯誤消失的方法,但每次都會複製資料。只需要讀取時,優先用 參考與借用。

函式與所有權


傳參數就是移動


把值傳給函式,跟指派給變數一樣:非 Copy 型別會移動進函式,函式結束時參數被 drop。下面這段無法編譯:
範例:
  1. fn shout(s: String) {
  2. println!("{}!", s.to_uppercase());
  3. }
  4. fn main() {
  5. let word = String::from("rust");
  6. shout(word);
  7. println!("原本的字:{}", word);
  8. }

輸出(編譯錯誤):
  1. error[E0382]: borrow of moved value: `word`
  2. --> main.rs:8:25
  3. |
  4. 6 | let word = String::from("rust");
  5. | ---- move occurs because `word` has type `String`, which does not implement the `Copy` trait
  6. 7 | shout(word);
  7. | ---- value moved here
  8. 8 | println!("原本的字:{}", word);
  9. | ^^^^ value borrowed here after move
  10. |
  11. note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary
  12. --> main.rs:1:13
  13. |
  14. 1 | fn shout(s: String) {
  15. | ----- ^^^^^^ this parameter takes ownership of the value
  16. | |
  17. | in this function
  18. help: consider cloning the value if the performance cost is acceptable
  19. |
  20. 7 | shout(word.clone());
  21. | ++++++++

rustc 的提示很實用:它建議把參數改成借用,或在呼叫端 .clone()。

回傳值把所有權交出去


函式回傳值時,所有權移給呼叫端。所以「拿進來、改一改、再還回去」是可行的寫法;Copy 型別(如 u32)傳進去後原變數仍可使用。
範例:
  1. fn shout(s: String) -> String {
  2. s.to_uppercase() + "!"
  3. }
  4. fn add_suffix(mut s: String) -> String {
  5. s.push_str("acean");
  6. s
  7. }
  8. fn count(n: u32) -> u32 {
  9. n * 2
  10. }
  11. fn main() {
  12. let word = String::from("rust");
  13. let loud = shout(word.clone());
  14. println!("{} -> {}", word, loud);
  15. let crab = add_suffix(word);
  16. println!("{}", crab);
  17. let n = 21;
  18. println!("{} -> {}", n, count(n));
  19. }

輸出:
  1. rust -> RUST!
  2. rustacean
  3. 21 -> 42

add_suffix 接手 word 之後又把結果回傳,所有權最後落在 crab。如果每次都要「傳進去再傳回來」會很囉唆,這正是參考存在的理由,見 參考與借用。

重點整理


  • 非 Copy 型別在指派、傳參數、for 迴圈時都會移動,原變數隨即失效(E0382)
  • Copy 型別(整數、浮點數、bool、char、&T、由它們組成的元組與陣列)會自動複製
  • 只有所有欄位都是 Copy 的型別才能 derive Copy,否則是 E0204
  • .clone() 明確地深複製整份資料,成本可能很高
  • 函式回傳值會把所有權交給呼叫端;只想讀取時傳參考而不是移動

資料來源