GolangUK talk:Stupid Gopher Tricks

Slide:Andrew Gerrand

Method values && Method expressions

method values和method expressions很难翻译,重点是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.

也就是说,如果直接引用类方法,其实就相当于直接引用这个方法,只不过需要多追加一个参数,即接收者:

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一样的方法,只不过会多出一个参数:接收者会追加为其第一个参数。结构如下:

func(tv T, a int) int

接收者有点像java中的this(实例),而这种方法和类方法很相似。一个小例子:

 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,会拥有这个变量,相当于接收者就是这个变量

var t T

表达式

t.Mv

会返回函数

func(int) int

这两个表达式相等

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)

总结:

不管是method expression还是method value都是function。前者是来自类型表达式,会在返回的函数中追加一个接收者;而后者,返回一个一模一样的函数。

你可能感兴趣的:(GolangUK talk:Stupid Gopher Tricks)