Last active
September 17, 2020 08:41
-
-
Save mathisve/54ec359d2e875b59162c9847b5d2d071 to your computer and use it in GitHub Desktop.
Golang interaces example, from: https://youtu.be/EGRXKV6j-v0
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 rectangle struct { | |
width float64 | |
height float64 | |
} | |
type circle struct { | |
radius float64 | |
} | |
type triangle struct { | |
height float64 | |
width float64 | |
b float64 | |
c float64 | |
} | |
func (r rectangle) area() float64 { | |
return r.height * r.width | |
} | |
func (c circle) area() float64 { | |
return math.Pi * math.Exp(c.radius) | |
} | |
func (t triangle) area() float64 { | |
return (t.height * t.width) / 2 | |
} | |
func (r rectangle) perim() float64 { | |
return (2 * r.height) + (2 * r.width) | |
} | |
func (c circle) perim() float64 { | |
return 2 * math.Pi * c.radius | |
} | |
func (t triangle) perim() float64 { | |
return t.width + t.b + t.c | |
} | |
type geometry interface { | |
area() float64 | |
perim() float64 | |
} | |
func calc (g geometry) { | |
fmt.Println("Area: ", g.area()) | |
fmt.Println("Perim:",g.perim()) | |
} | |
func main() { | |
rect := rectangle {height: 2, width: 5} | |
circle := circle {radius: 2} | |
tri := triangle {height: 2, width: 3, b: 3, c: 1} | |
for _, shape := range [3]geometry{rect, circle, tri} { | |
calc(shape) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment