go: interface example

Go is fresh fast relatively new language. One of the key to utilize it’s power are interfaces. Here is example of the geometry interfaces. See https://play.golang.org/p/nQ_ylb2jXKS

package main

import (
	"fmt"
	"math"
)

//https://www.mathsisfun.com/area.html

type geometry interface {
	area() float64
	perimeter() float64
}

type square struct {
	side float64
}
type rectangle struct {
	width, height float64
}
type triangle struct {
	a, b, c float64
}
type circle struct {
	radius float64
}

func (s square) area() float64 {
	return s.side * s.side
}
func (s square) perimeter() float64 {
	return 4 * s.side
}
func (r rectangle) area() float64 {
	return r.width * r.height
}
func (r rectangle) perimeter() float64 {
	return 2*r.width + 2*r.height
}
func (t triangle) area() float64 {
	cosGama := (t.c*t.c - t.a*t.a - t.b*t.b) / (2 * t.a * t.b)
	if math.Abs(cosGama) > 1.0 {
		fmt.Println("Input values are not for triangle")
		return -1
	}
	sinGama := math.Sqrt(1.0 - cosGama*cosGama)
	heightA := t.b * sinGama
	// fmt.Printf("triangle:  cos=%f, sin=%f,hA=%f\n",cosGama,sinGama,heightA)
	return t.a * heightA
}
func (t triangle) perimeter() float64 {
	return t.a + t.b + t.c
}
func (c circle) area() float64 {
	return math.Pi * c.radius * c.radius
}
func (c circle) perimeter() float64 {
	return 2 * math.Pi * c.radius
}
func measure(g geometry) {
	fmt.Println(g)
	fmt.Printf("area     : %f \n", g.area())
	fmt.Printf("perimeter: %f \n", g.perimeter())
}
func main() {
	s := square{side: 2}
	r := rectangle{width: 3, height: 4}
	t1 := triangle{a: 3, b: 4, c: 5}
	t2 := triangle{a: 1, b: 1, c: 1}
	t3 := triangle{a: 1, b: 1, c: 30}
	c := circle{radius: 5}
	
	measure(s)
	measure(r)
	measure(t1)
	measure(t2)
	measure(t3)
	measure(c)
}

This entry was posted in golang, workday. Bookmark the permalink.

Leave a Reply