From dd98c204463d93ec295263ebd022a3f9e1e42a9d Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 16 Sep 2012 15:20:57 -0700 Subject: [PATCH] more --- 34-embedding.go | 49 ++++++++++++++++++++++++++++++++++++++---------- 35-interfaces.go | 7 +++++++ 2 files changed, 46 insertions(+), 10 deletions(-) create mode 100644 35-interfaces.go diff --git a/34-embedding.go b/34-embedding.go index 596e456..544abca 100644 --- a/34-embedding.go +++ b/34-embedding.go @@ -1,22 +1,51 @@ package main import "fmt" +import "math" -type Person struct { - Name string +type Shape interface { + area() float64 } -func (p *Person) Talk() { - fmt.Println("Hi, my name is", p.Name) +type Circle struct { + x, y, r float64 } -type Android struct { - Person - Model string +func (c *Circle) area() float64 { + return math.Pi * c.r*c.r +} + +type Rectangle struct { + x1, y1, x2, y2 float64 +} + +func distance(x1, y1, x2, y2 float64) float64 { + a := x2 - x1 + b := y2 - y1 + return math.Sqrt(a*a + b*b) +} + +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 totalArea(shapes ...Shape) float64 { + var area float64 + for _, s := range shapes { + area += s.area() + } + return area } func main() { - android := new(Android) - android.Name = "Milo" - android.Talk() + circle := Circle{x: 0, y: 3, r: 5} + rectangle := Rectangle {x1: 3, x2: 10, y1: 5, y2: 7} + + area := 0.0 + for _, s := range []Shape{&circle, &rectangle} { + area += s.area() + } + fmt.Println(area) } diff --git a/35-interfaces.go b/35-interfaces.go new file mode 100644 index 0000000..0ebcbf2 --- /dev/null +++ b/35-interfaces.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +type Shape interface { + area() float64 +} \ No newline at end of file