結構體

最後更新


結構體(struct)把幾個相關的值包成一個有名字的型別,每個值稱為欄位(field),是 Rust 組織資料最基本的方式。

定義與建立


一本書有書名、頁數、能不能借,與其用三個獨立變數或一個看不出意義的元組 (String, u32, bool),不如定義一個 Book 型別,每個欄位都有名字。
寫法欄位存取適合
一般結構體 struct Book { title: String }book.title欄位多、需要名字說明意義
元組結構體 struct Meters(f64)m.0欄位少、包一層讓型別不會混用
單元結構體 struct Ready;沒有欄位只當標記,或用來實作特徵

定義結構體並建立實例


用 struct 名稱 { 欄位: 型別, ... } 定義;建立實例時每個欄位都要給值,順序可以和定義不同。用 實例.欄位 讀寫。型別名稱慣例用大駝峰(UpperCamelCase),欄位用蛇形(snake_case)。
範例:
  1. struct Book {
  2. title: String,
  3. pages: u32,
  4. available: bool,
  5. }
  6. fn main() {
  7. let mut book = Book {
  8. pages: 320,
  9. title: String::from("Rust 實戰秘笈"),
  10. available: true,
  11. };
  12. book.available = false;
  13. println!("《{}》共 {} 頁,可借:{}", book.title, book.pages, book.available);
  14. }

輸出:
  1. 《Rust 實戰秘笈》共 320 頁,可借:false

整個實例要 mut 才能改欄位


注意:Rust 不能只把某個欄位標成 mut,可變性屬於整個綁定。下面這段無法編譯,因為 book 沒有 mut:
範例:
  1. struct Book {
  2. title: String,
  3. pages: u32,
  4. }
  5. fn main() {
  6. let book = Book { title: String::from("草稿"), pages: 10 };
  7. book.pages = 12;
  8. println!("{} {}", book.title, book.pages);
  9. }

輸出(編譯錯誤):
  1. error[E0594]: cannot assign to `book.pages`, as `book` is not declared as mutable
  2. --> main.rs:8:5
  3. |
  4. 8 | book.pages = 12;
  5. | ^^^^^^^^^^^^^^^ cannot assign
  6. |
  7. help: consider changing this to be mutable
  8. |
  9. 7 | let mut book = Book { title: String::from("草稿"), pages: 10 };
  10. | +++

照提示寫 let mut book 就能修改任一欄位,如上一個範例。

欄位初始化簡寫


變數名稱和欄位名稱相同時,可以只寫一次:User { name, email, active: true } 等於 User { name: name, email: email, active: true }。常用在建構函式裡。
範例:
  1. struct User {
  2. name: String,
  3. email: String,
  4. active: bool,
  5. }
  6. fn new_user(name: String, email: String) -> User {
  7. User { name, email, active: true }
  8. }
  9. fn main() {
  10. let u = new_user(String::from("ann"), String::from("ann@example.com"));
  11. println!("{} <{}> active={}", u.name, u.email, u.active);
  12. }

輸出:
  1. ann <ann@example.com> active=true

結構體更新語法


用 ..base 沿用其他欄位


只想改幾個欄位、其他都沿用現有實例時,用 ..base,必須寫在最後。
範例:
  1. struct Config {
  2. host: String,
  3. port: u16,
  4. verbose: bool,
  5. }
  6. fn main() {
  7. let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
  8. let debug = Config { verbose: true, ..base };
  9. println!("{}:{} verbose={}", debug.host, debug.port, debug.verbose);
  10. }

輸出:
  1. localhost:8080 verbose=true

更新語法會移動欄位


..base 對每個沿用的欄位做的是「指派」,所以非 Copy 欄位(如 String)會被移動走(見 移動、複製與 Clone)。下面這段無法編譯:base.host 已經移到 debug。
範例:
  1. struct Config {
  2. host: String,
  3. port: u16,
  4. verbose: bool,
  5. }
  6. fn main() {
  7. let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
  8. let debug = Config { verbose: true, ..base };
  9. println!("{} {}", base.host, debug.port);
  10. }

輸出(編譯錯誤):
  1. error[E0382]: borrow of moved value: `base.host`
  2. --> main.rs:10:23
  3. |
  4. 9 | let debug = Config { verbose: true, ..base };
  5. | -------------------------------- value moved here
  6. 10 | println!("{} {}", base.host, debug.port);
  7. | ^^^^^^^^^ value borrowed here after move
  8. |
  9. = note: move occurs because `base.host` has type `String`, which does not implement the `Copy` trait

port 是 u16、verbose 是 bool,它們是複製過去的,所以 base.port 仍可使用,被移走的只有 host。如果之後還需要 base,就把非 Copy 的欄位明確 .clone():
範例:
  1. struct Config {
  2. host: String,
  3. port: u16,
  4. verbose: bool,
  5. }
  6. fn main() {
  7. let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
  8. let debug = Config { host: base.host.clone(), verbose: true, ..base };
  9. println!("base = {}:{} {}", base.host, base.port, base.verbose);
  10. println!("debug = {}:{} {}", debug.host, debug.port, debug.verbose);
  11. }

輸出:
  1. base = localhost:8080 false
  2. debug = localhost:8080 true

其他形式


元組結構體


元組結構體(tuple struct)的欄位沒有名字,只有型別,用 .0、.1 存取,也能用模式解構。常用來包一層讓型別更明確,這種寫法稱為 newtype:Meters 和 Feet 裡面都是 f64,但它們是不同型別,傳錯就編譯失敗。
範例:
  1. struct Meters(f64);
  2. struct Feet(f64);
  3. struct Rgb(u8, u8, u8);
  4. fn to_meters(f: Feet) -> Meters {
  5. Meters(f.0 * 0.3048)
  6. }
  7. fn main() {
  8. let m = to_meters(Feet(10.0));
  9. let Rgb(r, g, b) = Rgb(255, 128, 0);
  10. println!("{:.3} 公尺", m.0);
  11. println!("r={} g={} b={}", r, g, b);
  12. }

輸出:
  1. 3.048 公尺
  2. r=255 g=128 b=0

單元結構體


單元結構體(unit struct)完全沒有欄位,大小是 0 位元組。它本身不存資料,通常用來當作標記,或替它實作特徵(trait,見 特徵)。
範例:
  1. use std::mem::size_of;
  2. #[derive(Debug, PartialEq)]
  3. struct Ready;
  4. fn main() {
  5. let a = Ready;
  6. let b = Ready;
  7. println!("{:?} == {:?}:{}", a, b, a == b);
  8. println!("Ready 佔 {} 位元組", size_of::<Ready>());
  9. }

輸出:
  1. Ready == Ready:true
  2. Ready 佔 0 位元組

印出結構體


沒有 Debug 就不能用 {:?}


結構體預設不能被 println! 印出。{} 需要 Display、{:?} 需要 Debug,自訂型別兩者都沒有。下面這段無法編譯:
範例:
  1. struct Point {
  2. x: i32,
  3. y: i32,
  4. }
  5. fn main() {
  6. let p = Point { x: 1, y: 2 };
  7. println!("{:?}", p);
  8. }

輸出(編譯錯誤):
  1. error[E0277]: `Point` doesn't implement `Debug`
  2. --> main.rs:8:22
  3. |
  4. 8 | println!("{:?}", p);
  5. | ---- ^ `Point` cannot be formatted using `{:?}` because it doesn't implement `Debug`
  6. | |
  7. | required by this formatting parameter
  8. |
  9. = help: the trait `Debug` is not implemented for `Point`
  10. help: consider annotating `Point` with `#[derive(Debug)]`
  11. |
  12. 1 + #[derive(Debug)]
  13. 2 | struct Point {
  14. |

derive(Debug) 與 dbg!


在定義上方加 #[derive(Debug)],編譯器會自動產生 Debug 實作。{:?} 印成一行,{:#?} 換行縮排,適合欄位多的結構體。dbg!(運算式) 會把檔名、行號、運算式與值印到 stderr,並回傳那個值,除錯很方便。格式化的細節見 std::fmt。
範例:
  1. #[derive(Debug)]
  2. struct Point {
  3. x: i32,
  4. y: i32,
  5. }
  6. #[derive(Debug)]
  7. struct Line {
  8. start: Point,
  9. end: Point,
  10. }
  11. fn main() {
  12. let line = Line { start: Point { x: 0, y: 0 }, end: Point { x: 3, y: 4 } };
  13. println!("{:?}", line);
  14. println!("{:#?}", line.end);
  15. let dx = dbg!(line.end.x - line.start.x);
  16. let dy = dbg!(line.end.y - line.start.y);
  17. println!("平方長度 {}", dx * dx + dy * dy);
  18. }

輸出:
  1. Line { start: Point { x: 0, y: 0 }, end: Point { x: 3, y: 4 } }
  2. Point {
  3. x: 3,
  4. y: 4,
  5. }
  6. [main.rs:17:14] line.end.x - line.start.x = 3
  7. [main.rs:18:14] line.end.y - line.start.y = 4
  8. 平方長度 25

注意:derive 出來的 Debug 不算「讀取欄位」。如果某個欄位只在 {:?} 裡被印出,編譯器仍會警告 field is never read。

重點整理


  • struct 名稱 { 欄位: 型別 } 定義,建立時每個欄位都要給值,用 實例.欄位 存取
  • 可變性屬於整個實例,要改欄位就寫 let mut(E0594)
  • 欄位初始化簡寫 User { name, email } 與更新語法 ..base 讓建立實例更簡潔
  • ..base 會移動非 Copy 欄位,之後 base 的那些欄位就不能用(E0382)
  • 元組結構體做 newtype、單元結構體當標記
  • #[derive(Debug)] 後才能用 {:?}、{:#?} 與 dbg! 印出(否則 E0277)

資料來源