Home Interfaces
Post
Cancel

Interfaces

There is no inheritance in Go, but there are interfaces! Interfaces has methods and any type having the same methods satisfies that interface. In that sense, that type is an instance of that interface. So, in Go, you will not find extends or with. It just happens. In my personal opinion, you lose a bit of type self-documentation. Thus, there is no override either. So, unless I discover something interesting, you might rename a method and no longer satisfy an interface that the type used to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func main() {
	var s Speaker
	s = Person{"Muhammad"}
	s.speak()
}

type Speaker interface {
	speak()
}

type Person struct {
	name string
}

func (p Person) speak(){
	println("My name is", p.name)
}

Just to re-iterate, in the above example the type Person is a Speaker, because it has the method speak.

We can compose interfaces using type embedding.

1
2
3
4
5
6
7
8
9
10
11
12
 type Speaker interface {
 	speak()
 }
 
type SoccerPlayer interface {
	Play()
}

type SoccerSpeaker interface {
	Speaker
	SoccerPlayer
} 

So, if some type satisfies SoccerSpeaker it satisfies the other two as well.

Without explicit extension there is a probability that some one would refactor a piece of code without realizing that it satisfies one interface or the other. Turns out there is an ugly work around. By declaring a dummy variable in your type you can make it more explicit. It might be useful as documentation. But also, it helps your tooling to scream at you when you rename a function.

1
var _ Speaker = Person{}

Any or Object

In other languages such as Java or Scala there is a type that represents anything. In Java it is object and in Scala it is any. You can have the same effect by using interface {} in Go, since any type satisfies this interface. You will need type matching or some reflection magic to make use of the value you have passed though, which is the same as any other typed language.


Resources

  1. Ultimate Go Programming
  2. The Go Programming Language
  3. Go Documentation
  4. A tour of Go
  5. Go wiki: Switch
  6. The Go Programming Language Specification
  7. Go by Example
This post is licensed under CC BY 4.0 by the author.
Contents

Functions

Ruby Conditionals: if, else, elseif and unless

Comments powered by Disqus.