search

Explain the use of Go's interface types for defining common interfaces in Go programs?

Go's interface types provide a way to define a set of methods that a type must implement to satisfy the interface. Interfaces in Go are defined using the interface keyword followed by a set of method signatures. Any type that implements all the methods defined in the interface is said to satisfy the interface.

Here's an example of an interface definition:

type Shape interface {
    Area() float64
    Perimeter() float64
}

This interface defines two methods, **Area** and **Perimeter**, both of which return a **float64**. Any type that has these methods can satisfy this interface, regardless of the type's name or package.

Interfaces are commonly used to define common behaviors across multiple types. For example, you might define a **Drawable** interface that requires a type to have a **Draw** method, or a **Serializable** interface that requires a type to have a **Serialize** method.

To use an interface in Go, you simply define a variable of the interface type and assign a value to it that satisfies the interface. Here's an example:

type Rectangle struct {
    width  float64
    height float64
}

func (r Rectangle) Area() float64 {
    return r.width * r.height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.width + r.height)
}

func main() {
    var s Shape
    s = Rectangle{width: 2, height: 3}
    fmt.Println(s.Area())      // Output: 6
    fmt.Println(s.Perimeter()) // Output: 10
}

In this example, we define a **Rectangle** type that has **Area** and **Perimeter** methods. We then create a variable **s** of the **Shape** interface type and assign a **Rectangle** value to it. We can then call the **Area** and **Perimeter** methods on s as if it were a **Rectangle**. This is possible because **Rectangle** satisfies the **Shape** interface.

Related Questions You Might Be Interested