From f497e342f27e948482b425d5dca57e8edc6c3bd9 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Sun, 16 Sep 2012 14:53:41 -0700 Subject: [PATCH] more --- 32-fields.go | 15 +++++++++++++++ 33-methods.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 32-fields.go create mode 100644 33-methods.go diff --git a/32-fields.go b/32-fields.go new file mode 100644 index 0000000..6876fab --- /dev/null +++ b/32-fields.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +type Circle struct { + x, y, r int +} + +func main() { + c := Circle{x: 1, y: 2, r: 5} + fmt.Println(c.x, c.y, c.r) + c.x = 10 + c.y = 5 + fmt.Println(c.x, c.y, c.r) +} diff --git a/33-methods.go b/33-methods.go new file mode 100644 index 0000000..128fad2 --- /dev/null +++ b/33-methods.go @@ -0,0 +1,35 @@ +package main + +import "fmt" +import "math" + +type Circle struct { + x, y, r float64 +} + +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 main() { + circle := Circle{x: 0, y: 3, r: 5} + fmt.Println(circle.area()) + rectangle := Rectangle {x1: 3, x2: 10, y1: 5, y2: 7} + fmt.Println(rectangle.area()) +}