Interfaces
Interfaces are named collections of method signatures. They are the core of polymorphism in Go.Interface Definition
Implicit Implementation
A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.Interface Internals
Under the hood, an interface value is represented as a pair:(type, value) or more precisely (itab, data)
Where:
- itab (interface table): Contains type information and a pointer to the method table for the concrete type.
- data: Pointer to the actual value.
Interface Values with Nil Underlying Values
This is a common source of confusion. An interface can be in three states:- Nil interface: Both type and value are nil
(nil, nil) - Non-nil interface with nil value: Type is set, value is nil
(*T, nil) - Non-nil interface with non-nil value: Both are set
(*T, &value)
The Empty Interface
The interface type that specifies zero methods is known as the empty interface:fmt.Print takes any number of arguments of type interface{}.
Type Assertions
A type assertion provides access to an interface value’s underlying concrete 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.
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.