How to use the interface type in the Go language?

In the Go programming language, an interface is an abstract type that defines a collection of methods. Variables of interface type can store values of any concrete type that implements these methods. The steps for using an interface type are as follows:

  1. Please select the type.
  2. a way to connect or interact with something
type Shaper interface {
    Area() float64
    Perimeter() float64
}

The code above defines a Shaper interface that specifies two methods, Area() and Perimeter().

  1. Implement interface methods: To make a particular type implement an interface, simply implement all the methods defined in that interface on the type. For example:
type Rectangle struct {
    width, height float64
}

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

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

The above code defines a Rectangle type and implements the methods of the Shaper interface for it.

  1. Using interface types: You can declare variables using interface types and assign variables with specific types that implement the interface. For example:
var s Shaper
s = Rectangle{width: 5, height: 3}
fmt.Println(s.Area())
fmt.Println(s.Perimeter())

In the above code, a Rectangle value is assigned to a variable of interface type, and then the methods defined in the interface are called through this variable.

It’s important to note that interfaces in Go language are implemented implicitly, meaning that as long as a type implements all the methods defined in an interface, the type is considered to have implemented the interface without needing to explicitly declare it. This feature makes Go language interfaces very flexible and easy to use.

bannerAds