Anirban Mandal
Anirban Mandal

Reputation: 161

How to use function types in interfaces in Go

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?

Upvotes: 1

Views: 83

Answers (1)

icza
icza

Reputation: 418505

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.

Upvotes: 1

Related Questions