Home > Enterprise >  How to use function types in interfaces in Go
How to use function types in interfaces in Go

Time:03-13

I have the following code

type SomeInterface interface {
    SomeFunc(int, string)
}

type IntStringFunc func(int, string)

func (f IntStringFunc) SomeFunc(i int, s string) {
    f(i, s)
}

What is the syntax for invoking the method SomeFunc on the function type IntStringFunc?

CodePudding user response:

The method calling syntax does not depend on the receiver type, it's always the same: value.methodName(params).

For example:

var f IntStringFunc = func(i int, s string) {
    fmt.Printf("f(%d, %s)\n", i, s)
}

f.SomeFunc(1, "one")

This will output (try it on the Go Playground):

f(1, one)

Since type of f is a function type, you can of course call it too like this:

f(1, "one")

Which of course will print the same.

  • Related