Explained: Go interfaces

Stefan M.
Golicious
Published in
2 min readSep 24, 2019

In my previous blog (or question) I introduced something new:
An interface.

Simply put, an interface contains functions which have to be "implemented" by "something". The something is most probably a struct.

Compared to Java interfaces the Golang interfaces are pretty similar. Beside of the fact that there is no implements keyword. Well, in Kotlin there is also no implement keyword but there is some kind of "implementation" required for the classes who wants to be a type of this interface.
But what does this mean for go? Well, each type which "implement" all functions like an interface are automatically a type of this interface.

I think an example makes it more clear. Lets start with the Kotlin example:

interface StringToIntMapper {
fun map(string: String): Int
}
class DefaultStringToIntMapper : StringToIntMapper {
override fun map(string: String): Int {
return string.toInt()
}
}

As you see the implementation class DefaultStringToIntMapper has to implement the StringToIntMappper interface. Nothing special.

type StringToIntMapper interface {
Map(string string) int
}
type DefaultStringToIntMapper struct{}func (mapper DefaultStringToIntMapper) Map(string string) int {
i, _ := strconv.Atoi(string)
return i
}

On the Golang side we see that our DefaultStringToIntMapper struct knows zero about the interface. It has only one receiver function which has the same signature as the interface function. And this make the struct implicite a type of the interface!

That's it basically. If an interface has more functions a struct has to "implement" all of them of course.

Learning sources:

A little bit from my experiences about Java/Kotlin interfaces. But also here. The Golang tour has also a good explanation about receiver functions.

--

--