You are mixing two different things here. The one is that you define a type which is a function. When you want that type inside another type you need to use a struct.
Changing your code to a possible solution 1 (not so idiomatic go):
type MyMethod func(i int, j int, k int) (string, error)
type myMethodImpl struct {
Hello MyMethod
}
var hello MyMethod = func(i int, j int, k int) (string, error) {
return fmt.Sprintf("%d:%d:%d
", i, j, k), nil
}
func main() {
im := &myMethodImpl{Hello: hello}
fmt.Println(im.Hello(0, 1, 2))
}
https://play.golang.org/p/MH-WOnj-Mu
The other solution would be to change it to use an interface. That solution is your code just without the type definition of MyMethod. https://play.golang.org/p/nGctnTSwnC
But what is the difference between?
If you define a func as a type you need to declare it, when you create a function.
var hello MyMethod = func(i int, j int, k int) (string, error) {
return fmt.Sprintf("%d:%d:%d
", i, j, k), nil
}
Now hello
has just exactly the type MyMethod
. If there would be another type for example:
type YourMethod func(i int, j int, k int) (string, error)
hello
will still just the type MyMethod
.
To define an interface you need a method set. But the type MyMethod
is not a method. It is just a function type. So the function type is something different then a method definition. For go it would be the same if you want to define a string as a method.