Interface type defines a set of method signatures.
A value of interface type can hold any value that implements those methods.
Interfaces are implemented implicitly, aka Duck typing. There’s no explicit declaration like implements
keyword.
Interface value
Interface value under the hood can be thought of as a tuple of a value and a concrete type:
(value, type)
Calling a method on an interface value executes the method of the same name on its underlying type.
A nil
interface value holds neither value nor concrete type. Calling a method on a nil
interface will produce runtime error.
Calls with nil
receiver
When the value inside the interface is nil
, the method will be called with a nil
receiver.
In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method
M
in this example.)
Note that an interface value that holds a nil concrete value is itself non-nil.
Empty interface
The interface type that specifies zero methods is known as the empty interface:
Basically it’s any type, because all types implements at least zero methods.
Empty interfaces are used by code that handles values of unknown type. For example,
fmt.Print
takes any number of arguments of typeinterface{}
.
Type assertions
You can access an interface value’s underlying concrete value with:
This statement asserts that the interface value i
holds the concrete type T
and assigns the underlying T
value to the variable t
.
If i
does not hold a T
, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i
holds a T
, then t
will be the underlying value and ok
will be true.
If not, ok
will be false and t
will be the zero value of type T
, and no panic occurs.
Type switches
A type switch is a construct that permits several type assertions in series. It is like a regular switch statement, but the cases in a type switch specify types (not values).
The declaration in a type switch has the same syntax as a type assertion i.(T)
, but the specific type T
is replaced with the keyword type
.
Example: