Interfaces in Go

 Interfaces in Go


Go supports interfaces, which define a set of methods that a type must implement to satisfy the interface.



type Shape interface {

    Area() float64

}


type Rectangle struct {

    Width  float64

    Height float64

}


func (r Rectangle) Area() float64 {

    return r.Width * r.Height

}


var s Shape = Rectangle{3, 4}

fmt.Println(s.Area()) // prints 12.0

In this example, we define an interface called Shape with a single method called Area(). We then define a Rectangle struct that implements the Shape interface. We can then create a variable of type Shape and assign it a value of type Rectangle, and we can call the Area() method on the Shape variable.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...