Last active
December 17, 2015 22:38
-
-
Save michiel/5682888 to your computer and use it in GitHub Desktop.
Interface example in Go
This file contains 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 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