In following codes:
type of struct Struct.Test is void func(), the function can get all parameters in Struct t, why the types of Struct.func() and func() are the same
type Struct struct {
Val string
}
func (t *Struct) Test() {
println(t.Val)
}
func main() {
t := Struct{
Val: "Struct",
}
f := t.Test
f()
f = func() {
println("Hello world!")
}
f()
}
CodePudding user response:
t.Test is a method value:
If the expression
xhas static typeTandMis in the method set of typeT,x.Mis called a method value. The method valuex.Mis a function value that is callable with the same arguments as a method call ofx.M. The expressionxis 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 x.Test() method has no parameters, so x.Test is a function without parameters. The receiver x is saved internally and used when you call the x.Test function value later. Its type will be func(), so type of f is also func(), to which you can assign any value that also has a type of func().
Don't confuse method values with method expressions:
If
Mis in the method set of typeT,T.Mis a function that is callable as a regular function with the same arguments asMprefixed by an additional argument that is the receiver of the method.
The method expression is "applied" on a type, while a method value is "applied" on a value. Method expression results in a function value that includes the receiver type (as the first parameter), method value does not (the receiver is saved internally).
So in your case the method expression would be (*Struct).Test (note the pointer: Test() has pointer receiver), and it's a function with type func(Struct). It may be used / called like this:
f2 := (*Struct).Test
f2(&t)
Which again outputs Struct, try it on the Go Playground.
