Slide:Andrew Gerrand
Method values && Method expressions
method values和method expressions很難翻譯,重點(diǎn)是method這個詞也灰常難翻藻雪。直接用method來代替好了。golang spec文檔:
Method expressions:
If M is in the method set of type T, T.M is a function that is callable as a regular function with the same arguments as M prefixed by an additional argument that is the receiver of the method.
也就是說玫氢,如果直接引用類方法戒突,其實(shí)就相當(dāng)于直接引用這個方法,只不過需要多追加一個參數(shù),即接收者:
type T struct {
a int
}
func (tv T) Mv(a int) int { return 0 } // value receiver
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
var t T
the expression:
T.Mv
會返回一個和Mv一樣的方法氓鄙,只不過會多出一個參數(shù):接收者會追加為其第一個參數(shù)嚎京。結(jié)構(gòu)如下:
func(tv T, a int) int
接收者有點(diǎn)像java中的this(實(shí)例)嗡贺,而這種方法和類方法很相似。一個小例子:
var f func(*bytes.Buffer, string) (int, error)
var buf bytes.Buffer
f = (*bytes.Buffer).WriteString
f(&buf, "y u no buf.WriteString?")
buf.WriteTo(os.Stdout)
Method values
Method values
If the expression x has static type T and M is in the method set of type T, x.M is called a method value. The method value x.M is a function value that is callable with the same arguments as a method call of x.M. The expression x is evaluated and saved during the evaluation of the method value; the saved copy is then used as the receiver in any calls, which may be executed later.
The type T may be an interface or non-interface type.
簡單來說鞍帝,從變量直接賦值的method诫睬,會擁有這個變量,相當(dāng)于接收者就是這個變量
var t T
表達(dá)式
t.Mv
會返回函數(shù)
func(int) int
這兩個表達(dá)式相等
t.Mv(7)
f := t.Mv; f(7)
golang talk上的例子:
var f func(string) (int, error)
var buf bytes.Buffer
f = buf.WriteString f("Hey... ")
f("this *is* cute.")
buf.WriteTo(os.Stdout)
總結(jié):
不管是method expression還是method value都是function帕涌。前者是來自類型表達(dá)式,會在返回的函數(shù)中追加一個接收者摄凡;而后者,返回一個一模一樣的函數(shù)蚓曼。