方法
Rust 可讓您將函式與新型別建立關聯。您可以使用 impl 區塊來執行這項操作:
#[derive(Debug)]
struct Race {
name: String,
laps: Vec<i32>,
}
impl Race {
// No receiver, a static method
fn new(name: &str) -> Self {
Self { name: String::from(name), laps: Vec::new() }
}
// Exclusive borrowed read-write access to self
fn add_lap(&mut self, lap: i32) {
self.laps.push(lap);
}
// Shared and read-only borrowed access to self
fn print_laps(&self) {
println!("Recorded {} laps for {}:", self.laps.len(), self.name);
for (idx, lap) in self.laps.iter().enumerate() {
println!("Lap {idx}: {lap} sec");
}
}
// Exclusive ownership of self
fn finish(self) {
let total: i32 = self.laps.iter().sum();
println!("Race {} is finished, total lap time: {}", self.name, total);
}
}
fn main() {
let mut race = Race::new("Monaco Grand Prix");
race.add_lap(70);
race.add_lap(68);
race.print_laps();
race.add_lap(71);
race.print_laps();
race.finish();
// race.add_lap(42);
}
The self arguments specify the “receiver” - the object the method acts on. There are several common receivers for a method:
&self:使用共用且不可變動的參照,從呼叫端借用物件。之後可以再次使用該物件。&mut self:使用不重複且可變動的參照,從呼叫端借用物件。之後可以再次使用該物件。self:取得物件擁有權,並將其移出呼叫端。方法會成為物件的擁有者。系統會在方法傳回時捨棄物件 (取消分配),但如果其擁有權已明確傳送的情況例外。具備完整擁有權,不自動等同於具備可變動性。mut self: same as above, but the method can mutate the object.- 沒有接收器:這會成為結構體上的靜態方法,通常用於建立依慣例稱為
new的建構函式。
This slide should take about 8 minutes.
重點:
- 導入方法時,若將方法比做函式,會很有幫助。
- 系統會在型別的執行個體 (例如結構體或列舉) 上呼叫方法,第一個參數以
self代表執行個體。 - 開發人員可以選擇透過方法來充分利用方法接收器語法,以更有條理的方式進行整理。藉由使用方法,我們可以將所有實作程式碼存放在可預測的位置。
- 系統會在型別的執行個體 (例如結構體或列舉) 上呼叫方法,第一個參數以
- 指出我們會使用關鍵字
self,也就是方法接收器。- 說明
self是self: Self的縮寫,或許也能示範結構體名稱的可能用法。 - 講解
Self是impl區塊所屬型別的型別別名,可用於該區塊的其他位置。 - 提醒學員如何以類似於其他結構體的方式來使用
self,並指出點標記法可用來參照個別欄位, - This might be a good time to demonstrate how the
&selfdiffers fromselfby trying to runfinishtwice. - 除了
self的變體以外,您還可以使用特殊的包裝函式型別做為接收器型別,例如Box<Self>。
- 說明