Signature of methods?

Hello,
How can I get the signature of a method?
(I’m guessing it’s possible from: The Golang Tour, Methods, p.2, “Thou shall not forget methods are functions”)

I tried the following to highlight method’s signatures but got a compile error. I guess there is more to it.

package main

import (
	"fmt"
	"reflect"
)

type Test struct {
	Str string
}
type MyFuncType func(Test, string) string


func (t Test) hey1(s string) string {
	return t.Str
}

func hey2(t Test, s string) string {
	return t.Str
}

func main() {
	do(hey1, "a")
	do(hey2, "a")
}

func do(f MyFuncType, s string) {
	fmt.Println(reflect.TypeOf(f))
}
# command-line-arguments
./compile13.go:23:5: undefined: hey1

In your example, hey1 is a method on the Test struct.

That means you have to do this:

var foo Test
do(test.hey1, "a")

hey1 and hey2 are not the same.

func (t Test) hey1(s string) string is the signature of hey1
func hey2(t Test, s string) string is the signature of hey2.

By signature we mean the function name, input parameters and return type.

If I had a function func hello(s string) string that is not the same as function hello(s int) int

Did you mean ↓?

var foo Test
do(foo.hey1, "a")

That’s not what I’m looking for: here we’re passing to func do() the result of the hey1 method having received foo.
What I’m looking for is the signature of the method itself in order to pass it as variable, just like you would do with functions:

func do(f func(Test, string), s string) {
	//
}

Since the above work and since methods are functions, I’d like to do the following:

func do(f (Test) func(string), s string) {
	//
}

However that produces compile-time syntax errors

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.