From 0e7bf6a805f68798577f18cae0e678299b9b1d09 Mon Sep 17 00:00:00 2001 From: Michael Thomson Date: Sat, 25 May 2024 01:55:18 -0400 Subject: [PATCH] structs --- structs-methods-interfaces/shapes.go | 32 +++++++++++++++++++++++ structs-methods-interfaces/shapes_test.go | 30 +++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 structs-methods-interfaces/shapes.go create mode 100644 structs-methods-interfaces/shapes_test.go diff --git a/structs-methods-interfaces/shapes.go b/structs-methods-interfaces/shapes.go new file mode 100644 index 0000000..726816f --- /dev/null +++ b/structs-methods-interfaces/shapes.go @@ -0,0 +1,32 @@ +package structsmethodsinterfaces + +import "math" + +type Shape interface { + Area() float64 +} + +type Rectangle struct { + Width float64 + Height float64 +} + +func (r Rectangle) Area() float64 { + return r.Width * r.Height +} + +type Circle struct { + Radius float64 +} + +func (c Circle) Area() float64 { + return math.Pi * c.Radius * c.Radius +} + +func Perimeter(rectangle Rectangle) float64 { + return 2 * (rectangle.Width + rectangle.Height) +} + +func Area(rectangle Rectangle) float64 { + return rectangle.Width * rectangle.Height +} diff --git a/structs-methods-interfaces/shapes_test.go b/structs-methods-interfaces/shapes_test.go new file mode 100644 index 0000000..17752ef --- /dev/null +++ b/structs-methods-interfaces/shapes_test.go @@ -0,0 +1,30 @@ +package structsmethodsinterfaces + +import "testing" + +func TestPerimeter(t *testing.T) { + rectangle := Rectangle{10.0, 10.0} + got := Perimeter(rectangle) + want := 40.0 + + if got != want { + t.Errorf("got %.2f want %.2f", got, want) + } +} + +func TestArea(t *testing.T) { + areaTests := []struct { + shape Shape + want float64 + }{ + {Rectangle{12, 6}, 72.0}, + {Circle{10}, 314.1592653589793}, + } + + for _, tt := range areaTests { + got := tt.shape.Area() + if got != tt.want { + t.Errorf("got %g want %g", got, tt.want) + } + } +}