What is a Golang interface?
Thu Feb 11 2021tags: public draft golang programming computer science
Thanks to Liang Jun for this.
Question
What does the line
struct Something {
a []interface{}
}
actually mean? What is this interface
thingy, anyway?
Explanation
Say you have a program that reads and writes to a database. Your program is passed a InMemoryStore object that contains the functions read() and write(). The database object now could be an in-memory store, but maybe in future you want to make it a persistent store? It would be troublesome if we had to edit the way our program calls the database
This is where interfaces come in - we define Database as an interface that contains read() and write():
interface Database{
read()
write()
}
Instead of having our program directly operate on the InMemoryStore object, we make InMemoryStore implement the interface Database:
struct InMemoryStore { // implements Database
read() {...}
write() {...}
}
And have our program operate on the Database interface.
This means that in the future, if we want to swap the in-memory store to a persistent database, we just need to implement the persistent database to conform to the Database interface:
struct PersistentDB { // implements Database
read() {...}
write() {...}
}
And the beauty of this is that our program doesn't need to be changed, we just need to pass a PersistentDB instead of an InMemoryStore to it.
Interfaces as multiple inheritance
Interfaces can also be used to implement something like multiple inheritance:
interface WithdrawalMachine{
withdraw()
}
interface DepositMachine {
deposit()
}
struct ATM { // implements WithdrawalMachine, DepositMachine
withdraw() {...}
deposit() {...}
}
So what's []interface{} then??
In Golang, an object is considered to implicitly implement an interface if it implements all the methods of that interface. So let's say I have an interface and a struct:
interface MyInterface {
A()
B()
C()
}
struct MyStruct {
A()
B()
C()
D()
Z()
}
Because MyStruct implements all functions in MyInterface, Golang sees MyStruct as implementing MyInterface despite it never being explicitly declared anywhere.
Now consider the empty interface:
interface {
}
All structs in Golang implement it by default, since all structs implement "all" of its (zero) functions.
And therefore, a list of empty interfaces []interface{} basically means a list of Any
objects.