How to use function types in interfaces in Go

Issue

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?

Solution

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.

Answered By – icza

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.