Skip to content

Instantly share code, notes, and snippets.

@ifindev
Created July 4, 2022 10:38
Show Gist options
  • Save ifindev/94e55e4a9732b6723603b42d48e9a554 to your computer and use it in GitHub Desktop.
Save ifindev/94e55e4a9732b6723603b42d48e9a554 to your computer and use it in GitHub Desktop.
Go Interface for Polymorphism
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"math"
)
type Shape interface {
area() float64
}
func totalArea(shapes ...Shape) float64 {
var area float64
for _, s := range shapes {
area += s.area()
}
return area
}
type Circle struct {
x, y, r float64
}
func NewCircle(x, y, r float64) *Circle {
return &Circle{
x: x,
y: y,
r: r,
}
}
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
func NewRectangle(x1, y1, x2, y2 float64) *Rectangle {
return &Rectangle{
x1: x1,
y1: y1,
x2: x2,
y2: y2,
}
}
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
func (r *Rectangle) area() float64 {
l := distance(r.x1, r.y1, r.x1, r.y2)
w := distance(r.x1, r.y1, r.x2, r.y1)
return l * w
}
func main() {
c := NewCircle(0, 0, 2)
r := NewRectangle(0, 0, 2, 2)
fmt.Println(totalArea(c, r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment