Skip to content

Instantly share code, notes, and snippets.

@michiel
Last active December 17, 2015 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michiel/5682888 to your computer and use it in GitHub Desktop.
Save michiel/5682888 to your computer and use it in GitHub Desktop.
Interface example in Go
package main
import (
"fmt"
"math"
)
type Shaper interface {
SurfaceArea() float64
Volume() float64
}
type Cube struct {
side float64
}
func (c Cube) SurfaceArea() float64 {
return 6 * math.Pow(c.side, 2)
}
func (c Cube) Volume() float64 {
return math.Pow(c.side, 3)
}
type Sphere struct {
radius float64
}
func (s Sphere) SurfaceArea() float64 {
return 4 * math.Pi * math.Pow(s.radius, 2)
}
func (s Sphere) Volume() float64 {
return (4/3) * math.Pi * math.Pow(s.radius, 3)
}
func main() {
cube := Cube{side : 10}
sphere := Sphere{radius : 10}
shapes := [...]Shaper{cube, sphere}
for i, _ := range shapes {
fmt.Println("Shape #", i)
fmt.Printf("\tSurfaceArea : %g\n", shapes[i].SurfaceArea())
fmt.Printf("\tVolume : %g\n", shapes[i].Volume())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment