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()) +}