Convert Functions to Interfaces and vice versa in Go

How to convert a function to an interface in Go and how to convert an interface to a function

In this article, we will show how to use a function when your code expects an interface, and vice versa.

From Function to Interface

If you need to convert a function to a single-method interface, then you can define a method on the function type directly.

For instance, let’s say that you have the following function:

1
2
3
func funcName() string {
    return "https://takia.dev"
}

And you need an object implementing this interface in order to user the userCode function.

1
2
3
4
5
6
7
type Interface interface {
    MethodName() string
}

func userCode(i Interface) {
    println(i.MethodName())
}

The following code creates a user-defined function type and defines a method MethodName on that type:

1
2
3
4
5
type FuncType func() string

func (f FuncType) MethodName() string {
    return f()
}

Which let’s you easily convert between the function and the interface as follows:

1
2
var i Interface = FuncType(funcName)
userCode(i)

From Interface to Function

To use a single-method interface where a function is expected, simply pass the interface’s method:

Let’s say that you have an object implementing this interface:

1
2
3
type Interface interface {
    MethodName() string
}

And you want to use funcUserCode that requires a function object:

1
2
3
4
type FuncType func() string
func funcUserCode(f FuncType) {
    println(f())
}

Then, you can directly pass the method as argument:

1
2
3
4
func convert(myObject Interface) {
    var function FuncType = myObject.MethodName
    funcUserCode(myObject.MethodName)
}

Or you can wrap the method call in an anonymous function:

1
2
3
4
func convert(myObject Interface) {
    function := func() string { return i.MethodName() }
    funcUserCode(function)
}
© 2020-2025 Takia.Dev
Last updated on Aug 31, 2024 00:00 UTC