Interfaces
package main
import (
"fmt"
"math"
)
// Define an interface named 'geometry' with methods 'area' and 'perim'
type geometry interface {
area() float64
perim() float64
}
// Define a struct named 'rect' with two fields: 'width' and 'height'
type rect struct {
width, height float64
}
// Define a struct named 'circle' with a field 'radius'
type circle struct {
radius float64
}
// Implement the 'area' method for the 'rect' struct
func (r rect) area() float64 {
return r.width * r.height
}
// Implement the 'perim' method for the 'rect' struct
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
// Implement the 'area' method for the 'circle' struct
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
// Implement the 'perim' method for the 'circle' struct
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
// Function 'measure' takes a 'geometry' interface and prints information about it
func measure(g geometry) {
fmt.Println(g)
fmt.Println("Area:", g.area())
fmt.Println("Perimeter:", g.perim())
}
func main() {
// Create an instance of the 'rect' struct
r := rect{width: 3, height: 4}
// Create an instance of the 'circle' struct
c := circle{radius: 5}
// Call 'measure' function for the 'rect' instance
measure(r)
// Call 'measure' function for the 'circle' instance
measure(c)
}Output
Last updated