Implementation of Interfaces
Explore how to implement interfaces in Go to create flexible and reusable code. Understand type assertions, method sets on values and pointers, and how interfaces enable polymorphism and generalization in Go programs.
We'll cover the following...
Testing if a value implements an interface
This is a special case of the type assertion: suppose v is a value, and we want to test whether it implements the Stringer interface. This can be done as follows:
type Stringer interface { String() string }
if sv, ok := v.(Stringer); ok {
fmt.Printf("v implements String(): %s\n", sv.String()); // note: sv, not v
}
An interface is a kind of contract, which the implementing type(s) must fulfill. Interfaces describe the behavior of types, specifying what types can do. They completely separate the definition of what an object can do from how it does it, allowing distinct implementations to be represented at different times by the same interface variable, which is what polymorphism essentially is. Writing functions so that they accept an interface variable as a parameter makes them more general.
Note: Use interfaces to make your code ...