Methods - Comprehensive Rust 🦀
Rust
の文脈でいう「メソッド」は何らかの型に紐づくもの。(こちらで書いた関数は特に何らかの型に関連があるわけではない)
また、メソッドの最初の引数は関連する型(そのメソッドが定義された型)となる。
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn inc_width(&mut self, delta: u32) { self.width += delta; } } fn main() { let mut rect = Rectangle { width: 10, height: 5 }; println!("old area: {}", rect.area()); rect.inc_width(5); println!("new area: {}", rect.area()); }
所感
struct
キーワードで型を定義するのはまぁわかるが、impl
でわざわざ別のブロックでメソッドを定義することに若干の違和感。まぁこういうものなのだろう。