+28
Go/shapes/shapes.go
+28
Go/shapes/shapes.go
···
1
+
package shapes
2
+
3
+
import "math"
4
+
5
+
type Shape interface {
6
+
Area() float64
7
+
}
8
+
9
+
type Rectangle struct {
10
+
Width float64
11
+
Height float64
12
+
}
13
+
14
+
func (r Rectangle) Area() float64 {
15
+
return r.Width * r.Height
16
+
}
17
+
18
+
type Circle struct {
19
+
Radius float64
20
+
}
21
+
22
+
func (c Circle) Area() float64 {
23
+
return math.Pi * c.Radius * c.Radius
24
+
}
25
+
26
+
func Perimeter(rectangle Rectangle) float64 {
27
+
return 2 * (rectangle.Width + rectangle.Height)
28
+
}
+34
Go/shapes/shapes_test.go
+34
Go/shapes/shapes_test.go
···
1
+
package shapes
2
+
3
+
import "testing"
4
+
5
+
func TestPerimeter(t *testing.T) {
6
+
rectangle := Rectangle{10.0, 10.0}
7
+
got := Perimeter(rectangle)
8
+
want := 40.0
9
+
10
+
if got != want {
11
+
t.Errorf("got %.2f want %.2f", got, want)
12
+
}
13
+
}
14
+
15
+
func TestArea(t *testing.T) {
16
+
checkArea := func(t testing.TB, shape Shape, want float64) {
17
+
t.Helper()
18
+
got := shape.Area()
19
+
20
+
if got != want {
21
+
t.Errorf("got %g want %g", got, want)
22
+
}
23
+
}
24
+
25
+
t.Run("rectangles", func(t *testing.T) {
26
+
rectangle := Rectangle{12.0, 6.0}
27
+
checkArea(t, rectangle, 72.0)
28
+
})
29
+
30
+
t.Run("circles", func(t *testing.T) {
31
+
circle := Circle{10.0}
32
+
checkArea(t, circle, 314.1592653589793)
33
+
})
34
+
}