方法與關聯函式

最後更新


方法(method)是寫在 impl 區塊裡、第一個參數是 self 的函式;沒有 self 的則是關聯函式(associated function),最常見的是建構用的 new。

impl 區塊


Rust 沒有 class。資料用 結構體 或 列舉 定義,行為則另外寫在 impl 型別名 { ... } 裡。資料與行為分開寫,但呼叫時一樣用點號:rect.area()。

定義方法


方法的第一個參數是 &self,代表「借用呼叫這個方法的實例」,在方法內用 self.欄位 存取。其他參數照一般函式寫,例如 can_hold 再借用另一個 Rect。
範例:
  1. struct Rect {
  2. width: u32,
  3. height: u32,
  4. }
  5. impl Rect {
  6. fn area(&self) -> u32 {
  7. self.width * self.height
  8. }
  9. fn can_hold(&self, other: &Rect) -> bool {
  10. self.width >= other.width && self.height >= other.height
  11. }
  12. }
  13. fn main() {
  14. let big = Rect { width: 30, height: 20 };
  15. let small = Rect { width: 10, height: 5 };
  16. println!("面積:{}", big.area());
  17. println!("放得下:{}", big.can_hold(&small));
  18. println!("反過來:{}", small.can_hold(&big));
  19. }

輸出:
  1. 面積:600
  2. 放得下:true
  3. 反過來:false

self 的三種寫法


self 怎麼寫,決定方法對實例做什麼,規則和 參考與借用、移動 完全一致:
第一個參數等於方法能做什麼呼叫後實例
&selfself: &Self只讀照常可用
&mut selfself: &mut Self讀寫欄位照常可用
selfself: Self取得所有權,可以拆解或轉換被移走,不能再用

Self 是 impl 區塊所屬型別的別名,在 impl Counter 裡 Self 就是 Counter。

&self、&mut self、self


一個型別通常三種方法都有:查詢用 &self,修改用 &mut self,「最後一步」把自己轉成別的東西時用 self。
範例:
  1. struct Counter {
  2. label: String,
  3. count: u32,
  4. }
  5. impl Counter {
  6. fn get(&self) -> u32 {
  7. self.count
  8. }
  9. fn bump(&mut self) {
  10. self.count += 1;
  11. }
  12. fn finish(self) -> String {
  13. format!("{}:{}", self.label, self.count)
  14. }
  15. }
  16. fn main() {
  17. let mut c = Counter { label: String::from("點擊"), count: 0 };
  18. c.bump();
  19. c.bump();
  20. println!("目前 {}", c.get());
  21. let report = c.finish();
  22. println!("{}", report);
  23. }

輸出:
  1. 目前 2
  2. 點擊:2

呼叫 &mut self 方法需要 mut 綁定


注意:c.bump() 會自動借出 &mut c,所以 c 必須宣告成 let mut。下面這段無法編譯:
範例:
  1. struct Counter {
  2. count: u32,
  3. }
  4. impl Counter {
  5. fn bump(&mut self) {
  6. self.count += 1;
  7. }
  8. }
  9. fn main() {
  10. let c = Counter { count: 0 };
  11. c.bump();
  12. println!("{}", c.count);
  13. }

輸出(編譯錯誤):
  1. error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable
  2. --> main.rs:13:5
  3. |
  4. 13 | c.bump();
  5. | ^ cannot borrow as mutable
  6. |
  7. help: consider changing this to be mutable
  8. |
  9. 12 | let mut c = Counter { count: 0 };
  10. | +++

呼叫 self 方法會移走實例


注意:finish(self) 取得了 c 的所有權,呼叫後 c 就不能再用。下面這段無法編譯:
範例:
  1. struct Counter {
  2. label: String,
  3. count: u32,
  4. }
  5. impl Counter {
  6. fn finish(self) -> String {
  7. format!("{}:{}", self.label, self.count)
  8. }
  9. }
  10. fn main() {
  11. let c = Counter { label: String::from("點擊"), count: 3 };
  12. let report = c.finish();
  13. println!("{} / {}", report, c.count);
  14. }

輸出(編譯錯誤):
  1. error[E0382]: borrow of moved value: `c`
  2. --> main.rs:15:33
  3. |
  4. 13 | let c = Counter { label: String::from("點擊"), count: 3 };
  5. | - move occurs because `c` has type `Counter`, which does not implement the `Copy` trait
  6. 14 | let report = c.finish();
  7. | -------- `c` moved due to this method call
  8. 15 | println!("{} / {}", report, c.count);
  9. | ^^^^^^^ value borrowed here after move
  10. |
  11. note: `Counter::finish` takes ownership of the receiver `self`, which moves `c`
  12. --> main.rs:7:15
  13. |
  14. 7 | fn finish(self) -> String {
  15. | ^^^^

修法看需求:如果之後還要用 c,把 finish 改成 &self;如果 finish 本來就該是最後一步,就把要用的值在呼叫前先取出來。

關聯函式


用 new 建立實例


impl 裡沒有 self 參數的函式是關聯函式,用 型別::函式() 呼叫,不需要實例。Rust 沒有建構子(constructor)語法,慣例是寫一個回傳 Self 的 new;需要其他建立方式時再取有意義的名字,如 square、with_capacity。標準庫的 String::new()、Vec::new() 都是這個慣例。
範例:
  1. #[derive(Debug)]
  2. struct Rect {
  3. width: u32,
  4. height: u32,
  5. }
  6. impl Rect {
  7. fn new(width: u32, height: u32) -> Self {
  8. Self { width, height }
  9. }
  10. fn square(size: u32) -> Self {
  11. Self::new(size, size)
  12. }
  13. fn perimeter(&self) -> u32 {
  14. 2 * (self.width + self.height)
  15. }
  16. }
  17. fn main() {
  18. let r = Rect::new(4, 3);
  19. let s = Rect::square(5);
  20. println!("{:?} 周長 {}", r, r.perimeter());
  21. println!("{:?} 周長 {}", s, s.perimeter());
  22. let text = String::new();
  23. println!("String::new() 長度 {}", text.len());
  24. }

輸出:
  1. Rect { width: 4, height: 3 } 周長 14
  2. Rect { width: 5, height: 5 } 周長 20
  3. String::new() 長度 0

方法也能用路徑呼叫


r.area() 其實是 Rect::area(&r) 的簡寫。用點號呼叫時,編譯器會依方法的 self 型別自動補上 &、&mut 或解參考,這叫做自動參考與解參考(automatic referencing and dereferencing),所以 rr.area()、(&&r).area() 也都能呼叫。
範例:
  1. struct Rect {
  2. width: u32,
  3. height: u32,
  4. }
  5. impl Rect {
  6. fn area(&self) -> u32 {
  7. self.width * self.height
  8. }
  9. fn scale(&mut self, k: u32) {
  10. self.width *= k;
  11. self.height *= k;
  12. }
  13. }
  14. fn main() {
  15. let mut r = Rect { width: 2, height: 3 };
  16. println!("{} {}", r.area(), Rect::area(&r));
  17. r.scale(2);
  18. Rect::scale(&mut r, 10);
  19. let rr = &r;
  20. println!("{} {}", rr.area(), (&&r).area());
  21. }

輸出:
  1. 6 6
  2. 2400 2400

多個 impl 區塊


把方法分組


同一個型別可以有多個 impl 區塊,效果和寫在一起相同。常見用途是依用途分組,以及替型別實作特徵(trait),例如實作 fmt::Display 讓它能用 {} 印出(見 特徵 與 std::fmt)。
範例:
  1. use std::fmt;
  2. struct Temperature {
  3. celsius: f64,
  4. }
  5. impl Temperature {
  6. fn from_celsius(celsius: f64) -> Self {
  7. Self { celsius }
  8. }
  9. }
  10. impl Temperature {
  11. fn fahrenheit(&self) -> f64 {
  12. self.celsius * 9.0 / 5.0 + 32.0
  13. }
  14. fn is_freezing(&self) -> bool {
  15. self.celsius <= 0.0
  16. }
  17. }
  18. impl fmt::Display for Temperature {
  19. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  20. write!(f, "{:.1}°C", self.celsius)
  21. }
  22. }
  23. fn main() {
  24. let t = Temperature::from_celsius(-3.5);
  25. println!("{} = {:.1}°F,結冰:{}", t, t.fahrenheit(), t.is_freezing());
  26. }

輸出:
  1. -3.5°C = 25.7°F,結冰:true

重點整理


  • 方法寫在 impl 型別 { } 裡,第一個參數是 self,用 實例.方法() 呼叫
  • &self 只讀、&mut self 可改(需要 let mut,否則 E0596)、self 取走所有權(之後再用是 E0382)
  • 沒有 self 的是關聯函式,用 型別::函式() 呼叫;建構函式慣例命名為 new 並回傳 Self
  • 點號呼叫會自動補 &、&mut,r.area() 等於 Rect::area(&r)
  • 同一型別可以有多個 impl 區塊,特徵實作也寫在獨立的 impl 裡

資料來源