メソッド
最初のパラメタの名前が
self
の関連関数はメソッドと呼ばれ、通常の関数呼出記法と同様に、メソッド呼出演算子からも起動できる、これは例えばx.foo()
のようになる。
self
パラメタに型を指定する場合、それは以下の文法で生成されるどれかに解決できる型に制限される (ここで'lt
は任意のライフタイムを表す):P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P> S = Self | P
この文法での
Self
終端子は実装中の型へと解決される型を表す。これには、文脈上その型の別名となるSelf
や、他の型の別名、または実装型へと解決される関連型の写像も含まれる。// Examples of methods implemented on struct `Example`. struct Example; type Alias = Example; trait Trait { type Output; } impl Trait for Example { type Output = Example; } impl Example { fn by_value(self: Self) {} fn by_ref(self: &Self) {} fn by_ref_mut(self: &mut Self) {} fn by_box(self: Box<Self>) {} fn by_rc(self: Rc<Self>) {} fn by_arc(self: Arc<Self>) {} fn by_pin(self: Pin<&Self>) {} fn explicit_type(self: Arc<Example>) {} fn with_lifetime<'a>(self: &'a Self) {} fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {} fn via_projection(self: <Example as Trait>::Output) {} }