Interfaces in Go are a set of methods that defines a behavior. A type can implement an interface by defining methods with the same signatures as the methods defined in the interface. This allows for a form of polymorphism in Go, where a single function or method can operate on values of different types, as long as those types implement the required interface.
One of the key concepts of interfaces in Go is that they are implicitly satisfied, meaning that a type does not need to explicitly state that it implements an interface. If a type has methods with the same signatures as the methods defined in an interface, it is considered to implement the interface.
Here’s a simple example that demonstrates the basic concepts of interfaces in Go:
package main import "fmt" // The Printer interface defines the behavior for a type that can print itself. type Printer interface { Print() } // The Rectangle type implements the Printer interface by defining the Print method. type Rectangle struct { width, height int } func (r Rectangle) Print() { fmt.Printf("Rectangle: width=%d, height=%d\n", r.width, r.height) } // The Circle type implements the Printer interface by defining the Print method. type Circle struct { radius int } func (c Circle) Print() { fmt.Printf("Circle: radius=%d\n", c.radius) } func main() { // Create a slice of Printer values. shapes := []Printer{Rectangle{2, 3}, Circle{4}} // Loop over the slice of Printer values and call the Print method for each value. for _, shape := range shapes { shape.Print() } }
In this example, we define an interface called Printer that has a single method, Print. We then define two types, Rectangle and Circle, that implement the Printer interface by defining the Print method.
In the main function, we create a slice of Printer values and loop over the slice, calling the Print method for each value. Since both the Rectangle and Circle types implement the Printer interface, we can store values of both types in a single slice of Printer values.
This example demonstrates the key concepts of interfaces in Go, including how to define an interface, how to implement an interface, and how to use values of different types in a single slice, as long as those types implement the required interface.
Interfaces in Go provide a powerful way to define behavior that can be shared across different types, and they are a fundamental part of the Go programming language. By understanding the basic concepts of interfaces, Go programmers can build more flexible and reusable code, and write programs that are more easily maintainable and scalable.
More knowledge keyword on Go Interface
Object-Oriented Design (OOD)
Procedural programming
Protocol-Oriented Programming (POP)