Interfaces and Dynamic Typing

This lesson shows how well Go handles dynamic typing as compared to other languages and reveals how Go saves us from a hustle with the implementation of interfaces.

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 implementing an interface can be passed to any function that takes that interface as an argument.

This resembles the duck typing in dynamic languages like Python and Ruby; this can be defined to mean that objects can be handled (e.g., passed to functions) based on the methods they provide, regardless of their actual types: what they are is less important than what they can do.

This is illustrated in the following program:

Get hands-on with 1200+ tech skills courses.