structs
This commit is contained in:
parent
cd509e9acd
commit
0e7bf6a805
32
structs-methods-interfaces/shapes.go
Normal file
32
structs-methods-interfaces/shapes.go
Normal file
@ -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
|
||||
}
|
30
structs-methods-interfaces/shapes_test.go
Normal file
30
structs-methods-interfaces/shapes_test.go
Normal file
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user