Learning GoLang - Day 4 : Go Interface that you may not think about
Keywords: interface proliferation; duck typing
The "Overloaded" Interface
Duck Typing
"If it walks like a duck and it quacks like a duck, then it must be a duck."[^1] [^1]: Wikipedia
Think about the definition of the interface.
It is a type, it is an abstract type waiting to be implemented, it specifies a set of methods that a concrete type must implement, and it serves as a way to define common behavior that multiple types(polymorphism) can share.
Based on the above baseline, Go Interfaces are overloaded with some additional features:
- Every type has an interface.
- A Go interface type == a set of methods.
- No explicit declaration for a valid implementation.
Go interfaces are implemented by a form of duck typing(not purely1). In a language supporting duck typing, an object could be considered as an instance of a type only if its methods or features are supported by this object, even though there is no explicit declaration. In other words, an object's suitability is determined not by its type itself, but by its behavior. It also supports type conversion in a dynamic way(checking at runtime).
Interface Pollution
From ChatGPT 3.5
Interface Pollution: Interface pollution refers to the situation where there are too many interfaces in a codebase, making it harder to understand and maintain. It's a problem because excessive use of interfaces can lead to unnecessary complexity.
Interface pollution is not a fancy concept, but a topic worth discussing. Unlike languages like C++ or Java, where abstract types and interfaces are commonly used to initiate a codebase, Go encourages a different approach. In Go, it's recommended to start with concrete types and only introduce interfaces when necessary. This is contrary to the traditional object-oriented programming approach. The interface design in Go uses a pragmatic approach, emphasizing simplicity and clarity in codebase design and discouraging unnecessary abstraction and interface proliferation.
It allows users to define on-the-fly interface definitions in their scopes and facilitates mockability and testability.
Internals Mechanism
Go doesn't use a traditional dispatch table, but a tiny lookup hash table for the concrete type it's pointing to. I am not going to dive too much into this, to avoid being stuck only after four days of learning Go, but you are free to check more details in the reading resources at the end of this blog.
Some other interesting facts about Go Interfaces
- An interface value that holds a nil concrete value is itself non-nil.
- A nil interface value holds neither value nor concrete type.
- An empty interface has zero methods.
See you tomorrow, let's move to the next chapter of GoLang!
More Readings
Because the Go compiler will statically check the interface type implementation when possible.↩