Interfaces and Dynamic Typing
Learn how Go's interfaces enable dynamic typing with static checks, allowing types to implicitly implement interfaces. Discover type assertions, interface embedding, and how this design supports flexible, maintainable code without altering existing types.
Dynamic typing in Go
In classical OO languages (like C++, Java, and C#) data and the methods which act upon that data are united in the class-concept: a class contains them both, they cannot be separated. In Go, there are no classes: data (structures, or more general types) and methods are treated orthogonally. They are much more loosely coupled.
Interfaces in Go are similar to their Java/C# counterparts; both specify a minimum set of methods that an implementer of an interface must provide. However, they are also more fluid and generic: any type that provides code for the methods of an interface implicitly implements that interface, without having to say explicitly that it does.
Compared to other languages, Go is the only one that combines interface values, static type checking (does a type implement the interface?), dynamic runtime conversion, and no requirement for explicitly declaring that a type satisfies an interface. This property also allows interfaces to be defined and used without having to modify existing code.
A function that has one or more parameters of an interface type can be called with a variable whose type implements that interface. Types ...