Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shockalotti/72532ce3a20cfe2105ca to your computer and use it in GitHub Desktop.
Save shockalotti/72532ce3a20cfe2105ca to your computer and use it in GitHub Desktop.
Go Golang - structs, methods, embedded types, interfaces example
package main
import ("fmt"; "math")
// interfaces
type Shaper interface {
area() float64
perimeter() float64
}
// structs
type Circle struct {
x, y, r float64
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
// methods
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
func (c *Circle) perimeter() float64 {
return math.Pi * 2 * c.r
}
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 (r *Rectangle) perimeter() float64 {
return 2 * (r.x2 - r.x1) + 2* (r.y2 - r.y1)
}
// functions
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
func totalArea(shapes ... Shaper) float64 {
var area float64
for _, s := range shapes {
area += s.area()
}
return area
}
func totalPerimeter(shapes ... Shaper) float64 {
var perimeter float64
for _, s := range shapes {
perimeter += s.perimeter()
}
return perimeter
}
func main() {
c := Circle{0, 0, 5}
r := Rectangle{0, 0, 10, 10}
fmt.Println("Area of circle is",c.area())
fmt.Println("Area of rectangle is",r.area())
fmt.Println("Total area of shapes is",totalArea(&c, &r))
fmt.Println("Perimeter of circle is",c.perimeter())
fmt.Println("Perimeter of rectangle is",r.perimeter())
fmt.Println("Total perimeter of shapes is",totalPerimeter(&c, &r))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment