Last active
August 2, 2022 21:14
-
-
Save royvandam/1bdb6b3d345200b2acb3646891ff9b92 to your computer and use it in GitHub Desktop.
Golang "inheritance" by composition and polymorphic classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
type ( | |
Shape interface { | |
GetCoords() (float64, float64) | |
GetType() string | |
GetArea() float64 | |
} | |
) | |
type shapeBase struct { | |
X float64 | |
Y float64 | |
} | |
func (s *shapeBase) GetCoords() (float64, float64) { | |
return s.X, s.Y | |
} | |
type Circle struct { | |
shapeBase | |
Radius float64 | |
} | |
func NewCircle(x, y, radius float64) *Circle { | |
return &Circle{shapeBase: shapeBase{X: x, Y: y}, Radius: radius} | |
} | |
func (c *Circle) GetType() string { | |
return "circle" | |
} | |
func (c *Circle) GetArea() float64 { | |
return 2 * math.Pi * c.Radius | |
} | |
type Rectangle struct { | |
shapeBase | |
Width float64 | |
Height float64 | |
} | |
func NewRectangle(x, y, w, h float64) *Rectangle { | |
return &Rectangle{shapeBase: shapeBase{X: x, Y: y}, Width: w, Height: h} | |
} | |
func (r *Rectangle) GetType() string { | |
return "rectangle" | |
} | |
func (r *Rectangle) GetArea() float64 { | |
return r.Width * r.Height | |
} | |
func PrintShapes(shapes []Shape) { | |
for _, s := range shapes { | |
x, y := s.GetCoords() | |
fmt.Printf("position: (%.2f, %.2f), type: %s, area: %.2f\n", | |
x, y, | |
s.GetType(), | |
s.GetArea()) | |
} | |
} | |
func main() { | |
shapes := []Shape{ | |
NewCircle(100, 100, 3), | |
NewRectangle(50, 50, 10, 60), | |
} | |
PrintShapes(shapes) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
roy@desktop:~/Projects/scratch/poly$ go build poly.go | |
roy@desktop:~/Projects/scratch/poly$ ./poly | |
position: (100.00, 100.00), type: circle, area: 18.85 | |
position: (50.00, 50.00), type: rectangle, area: 600.00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment