Interfaces in 2 mins
I had to explain interfaces to my colleagues learning Go, this was my second (and better) attempt!
Hey guys!
Long time no speak. I hope 2021 is going well for you?!
In this newsletter I’m sharing, something I fired over to a couple of my colleagues who are learning Go. I’m supposed to be helping them.
Hey both.
I think I did a poor job of explaining interfaces on Monday. So I wanted to summarise, as I think this is the crux of it.Because Go is a statically typed language - a variable can never store a different type - code can get verbose and repeated when trying to perform similar operations on all the different types.
There's a couple of ways this can show itself, but here's an example. I have two types “cat” and “dog”, both have a name property.
Without interfaces it would be verbose to get them to speak their name. I would need a function for each type.
See this example: https://play.golang.org/p/9WuJvjqUBnz
Imagine what happens as we add more animals? We would need more type specific code to make them speak!
Interfaces let us use types, based not on what they are i.e. a dog, or a cat, but what they can do. We call this behaviour.
In this example, see how if things have the same “behaviours”, we can treat them the same way: https://play.golang.org/p/kwt4mYxaPms
This sort of approach is often referred to as “duck-typing”.
At first sight, there’s not much less code (there’s more TBH), but see how this is easier to maintain as we add more animals, also see how it would be possible to range over a slice of types that are “animals” in a loop. It would be difficult to do this on concrete types without using an empty interface and then getting into reflection - which itself would need to be appended to every time we added a new animal.
Hope that's a bit more useful :)