What are interfaces used for in Go?
In Go, interfaces define a set of methods that a type must implement in order to satisfy the interface. Interfaces enable a high degree of flexibility and polymorphism in Go code, allowing developers to write more modular and extensible programs.
An interface is declared using the **interface**
keyword, followed by the list of method signatures that must be implemented by any type that satisfies the interface. Here's an example:
type Shape interface {
Area() float64
Perimeter() float64
}
This interface, called **Shape**
, defines two methods: **Area**
and **Perimeter**
. Any type that implements these two methods can be considered a **Shape**
.
For example, we can define a **Circle**
type that satisfies the **Shape**
interface:
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
In this example, the **Circle**
type has an **Area**
method and a **Perimeter**
method, both of which have the appropriate method signature to satisfy the **Shape**
interface. Therefore, we can say that **Circle**
is a **Shape**
.
Interfaces in Go can also be used in a variety of other ways, such as embedding interfaces within other interfaces, and using interfaces as function parameters and return types. Overall, interfaces are a powerful feature of Go that enable developers to write more modular and extensible code.