方法與關聯函式
最後更新
方法(method)是寫在
impl 區塊裡、第一個參數是 self 的函式;沒有 self 的則是關聯函式(associated function),最常見的是建構用的 new。impl 區塊
Rust 沒有 class。資料用 結構體 或 列舉 定義,行為則另外寫在
impl 型別名 { ... } 裡。資料與行為分開寫,但呼叫時一樣用點號:rect.area()。定義方法
方法的第一個參數是
&self,代表「借用呼叫這個方法的實例」,在方法內用 self.欄位 存取。其他參數照一般函式寫,例如 can_hold 再借用另一個 Rect。範例:
- struct Rect {
- width: u32,
- height: u32,
- }
- impl Rect {
- fn area(&self) -> u32 {
- self.width * self.height
- }
- fn can_hold(&self, other: &Rect) -> bool {
- self.width >= other.width && self.height >= other.height
- }
- }
- fn main() {
- let big = Rect { width: 30, height: 20 };
- let small = Rect { width: 10, height: 5 };
- println!("面積:{}", big.area());
- println!("放得下:{}", big.can_hold(&small));
- println!("反過來:{}", small.can_hold(&big));
- }
輸出:
- 面積:600
- 放得下:true
- 反過來:false
self 的三種寫法
self 怎麼寫,決定方法對實例做什麼,規則和 參考與借用、移動 完全一致:| 第一個參數 | 等於 | 方法能做什麼 | 呼叫後實例 |
|---|---|---|---|
&self | self: &Self | 只讀 | 照常可用 |
&mut self | self: &mut Self | 讀寫欄位 | 照常可用 |
self | self: Self | 取得所有權,可以拆解或轉換 | 被移走,不能再用 |
Self 是 impl 區塊所屬型別的別名,在 impl Counter 裡 Self 就是 Counter。&self、&mut self、self
一個型別通常三種方法都有:查詢用
&self,修改用 &mut self,「最後一步」把自己轉成別的東西時用 self。範例:
- struct Counter {
- label: String,
- count: u32,
- }
- impl Counter {
- fn get(&self) -> u32 {
- self.count
- }
- fn bump(&mut self) {
- self.count += 1;
- }
- fn finish(self) -> String {
- format!("{}:{}", self.label, self.count)
- }
- }
- fn main() {
- let mut c = Counter { label: String::from("點擊"), count: 0 };
- c.bump();
- c.bump();
- println!("目前 {}", c.get());
- let report = c.finish();
- println!("{}", report);
- }
輸出:
- 目前 2
- 點擊:2
呼叫 &mut self 方法需要 mut 綁定
注意:
c.bump() 會自動借出 &mut c,所以 c 必須宣告成 let mut。下面這段無法編譯:範例:
- struct Counter {
- count: u32,
- }
- impl Counter {
- fn bump(&mut self) {
- self.count += 1;
- }
- }
- fn main() {
- let c = Counter { count: 0 };
- c.bump();
- println!("{}", c.count);
- }
輸出(編譯錯誤):
- error[E0596]: cannot borrow `c` as mutable, as it is not declared as mutable
- --> main.rs:13:5
- |
- 13 | c.bump();
- | ^ cannot borrow as mutable
- |
- help: consider changing this to be mutable
- |
- 12 | let mut c = Counter { count: 0 };
- | +++
呼叫 self 方法會移走實例
注意:
finish(self) 取得了 c 的所有權,呼叫後 c 就不能再用。下面這段無法編譯:範例:
- struct Counter {
- label: String,
- count: u32,
- }
- impl Counter {
- fn finish(self) -> String {
- format!("{}:{}", self.label, self.count)
- }
- }
- fn main() {
- let c = Counter { label: String::from("點擊"), count: 3 };
- let report = c.finish();
- println!("{} / {}", report, c.count);
- }
輸出(編譯錯誤):
- error[E0382]: borrow of moved value: `c`
- --> main.rs:15:33
- |
- 13 | let c = Counter { label: String::from("點擊"), count: 3 };
- | - move occurs because `c` has type `Counter`, which does not implement the `Copy` trait
- 14 | let report = c.finish();
- | -------- `c` moved due to this method call
- 15 | println!("{} / {}", report, c.count);
- | ^^^^^^^ value borrowed here after move
- |
- note: `Counter::finish` takes ownership of the receiver `self`, which moves `c`
- --> main.rs:7:15
- |
- 7 | fn finish(self) -> String {
- | ^^^^
修法看需求:如果之後還要用
c,把 finish 改成 &self;如果 finish 本來就該是最後一步,就把要用的值在呼叫前先取出來。關聯函式
用 new 建立實例
impl 裡沒有 self 參數的函式是關聯函式,用 型別::函式() 呼叫,不需要實例。Rust 沒有建構子(constructor)語法,慣例是寫一個回傳 Self 的 new;需要其他建立方式時再取有意義的名字,如 square、with_capacity。標準庫的 String::new()、Vec::new() 都是這個慣例。範例:
- #[derive(Debug)]
- struct Rect {
- width: u32,
- height: u32,
- }
- impl Rect {
- fn new(width: u32, height: u32) -> Self {
- Self { width, height }
- }
- fn square(size: u32) -> Self {
- Self::new(size, size)
- }
- fn perimeter(&self) -> u32 {
- 2 * (self.width + self.height)
- }
- }
- fn main() {
- let r = Rect::new(4, 3);
- let s = Rect::square(5);
- println!("{:?} 周長 {}", r, r.perimeter());
- println!("{:?} 周長 {}", s, s.perimeter());
- let text = String::new();
- println!("String::new() 長度 {}", text.len());
- }
輸出:
- Rect { width: 4, height: 3 } 周長 14
- Rect { width: 5, height: 5 } 周長 20
- String::new() 長度 0
方法也能用路徑呼叫
r.area() 其實是 Rect::area(&r) 的簡寫。用點號呼叫時,編譯器會依方法的 self 型別自動補上 &、&mut 或解參考,這叫做自動參考與解參考(automatic referencing and dereferencing),所以 rr.area()、(&&r).area() 也都能呼叫。範例:
- struct Rect {
- width: u32,
- height: u32,
- }
- impl Rect {
- fn area(&self) -> u32 {
- self.width * self.height
- }
- fn scale(&mut self, k: u32) {
- self.width *= k;
- self.height *= k;
- }
- }
- fn main() {
- let mut r = Rect { width: 2, height: 3 };
- println!("{} {}", r.area(), Rect::area(&r));
- r.scale(2);
- Rect::scale(&mut r, 10);
- let rr = &r;
- println!("{} {}", rr.area(), (&&r).area());
- }
輸出:
- 6 6
- 2400 2400
多個 impl 區塊
把方法分組
同一個型別可以有多個
impl 區塊,效果和寫在一起相同。常見用途是依用途分組,以及替型別實作特徵(trait),例如實作 fmt::Display 讓它能用 {} 印出(見 特徵 與 std::fmt)。範例:
- use std::fmt;
- struct Temperature {
- celsius: f64,
- }
- impl Temperature {
- fn from_celsius(celsius: f64) -> Self {
- Self { celsius }
- }
- }
- impl Temperature {
- fn fahrenheit(&self) -> f64 {
- self.celsius * 9.0 / 5.0 + 32.0
- }
- fn is_freezing(&self) -> bool {
- self.celsius <= 0.0
- }
- }
- impl fmt::Display for Temperature {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{:.1}°C", self.celsius)
- }
- }
- fn main() {
- let t = Temperature::from_celsius(-3.5);
- println!("{} = {:.1}°F,結冰:{}", t, t.fahrenheit(), t.is_freezing());
- }
輸出:
- -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裡