Commit b77aa05
Changed files (5)
bin/examples
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+go test -v
perimeter.go
@@ -1,14 +0,0 @@
-package main
-
-type Rectangle struct {
- Width float64
- Height float64
-}
-
-func Perimeter(rectangle Rectangle) float64 {
- return 2 * (rectangle.Width + rectangle.Height)
-}
-
-func Area(rectangle Rectangle) float64 {
- return rectangle.Width * rectangle.Height
-}
perimeter_test.go
@@ -1,25 +0,0 @@
-package main
-
-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) {
- rectangle := Rectangle{12.0, 6.0}
- got := Area(rectangle)
- want := 72.0
-
- if got != want {
- t.Errorf("got %.2f want %.2f", got, want)
- }
-}
shapes.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "math"
+)
+
+func Perimeter(rectangle Rectangle) float64 {
+ return 2 * (rectangle.Width + rectangle.Height)
+}
+
+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
+}
shapes_test.go
@@ -0,0 +1,35 @@
+package main
+
+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) {
+ tests := []struct {
+ name string
+ shape Shape
+ want float64
+ }{
+ {"rectangles", Rectangle{12, 6}, 72.0},
+ {"circles", Circle{10}, 314.1592653589793},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ got := test.shape.Area()
+ if got != test.want {
+ t.Errorf("got %g want %g", got, test.want)
+ }
+ })
+ }
+}