Home > Blockchain >  Why are structure functions the same type as ordinary functions
Why are structure functions the same type as ordinary functions

Time:09-22

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 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 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 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.

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.

  • Related