「所有的trait都定義了乙個隱式的型別self,它指當前實現此介面的型別。」 ——rust官方文件
當self
用作函式的第乙個引數時,它等價於self: self
。&self
引數等價於self: &self
。&mut self
引數等價於self: &mut self
。
方法引數中的self
是一種語法糖,是方法的接收型別(例如,本方法所在的impl
的型別)。
它可能出現在trait
或impl
中。但經常出現在trait
中,它是任何最終實現trait
的型別代替(在定義trait
時未知該型別)。
trait clone
我們有乙個結構體類型別mytype
,它實現了這個trait
。
impl clone for mytype
self
是trait
或impl
中方法的第乙個引數名。使用其他引數名是可能的,但有顯著的差異:
在rust中,沒有隱式傳遞this
引數給某個型別的方法。你得顯式將「當前物件」傳遞給方法引數。這將導致:
正如我們所見,作為一種較短的寫法,這也可能(仍然冗長):impl mytype
}
因此,對照表:impl mytype
}
但呼叫這些函式的方式變了:self => self: self
&self => self: &self
&mut self => self: &mut self
樣例來自《深入淺出rust》,我稍加擴充套件,作為演示功能用。impl mytype
fn another(this: &self, a: u32)
}fn main()
fn main() ;
println!("the area is {}",c.area());
println!("the area is {}",circle::area2(&c))
}trait shape
struct circle
impl shape for circle
fn area2(this: &circle) -> f64
}
Swift3 0 Self和self的區別
相信大家都知道self關鍵字的作用,但你知道swift還有個self關鍵字嗎?self關鍵字只能用在類裡,作為函式返回值型別,表示當前類。類定義.png 這段 裡有self和self,self指向類自身 self只能作為函式關鍵字,setvalue函式的返回值是classa型別。我們看到有個warn...
顯式self和隱式self的區別
1.class diffself public def method1 puts call method1 enddef method2 puts call method2 self.method1 enddef method3 puts call method3 method1 endend t ...
self和static的區別
self引用的是當前類,static允許函式呼叫在執行時繫結呼叫類 簡單來說,就是使用self返回的值一直是初始類,而static的繼承類返回的值是離它最近的類內部的資料。舉個例子 self是乙個只認爸媽的小孩,而static是誰帶著它就認誰的小孩 class car protected stati...