Perimeter(width float64, height float64)
float64
是形如 123.45
的浮点数。f
对应 float64
,.2
表示输出 2 位小数。./shapes_test.go:6:9: undefined: Perimeter
shapes_test.go:10: got 0 want 40
myStruct.field
./shapes_test.go:28:13: undefined: Circle
./shapes_test.go:29:14: cannot use circle (type Circle) as type Rectangle in argument to Area
./shapes.go:20:32: Area redeclared in this block
type Circle has no field or method Area
func(receiverName ReceiverType) MethodName(args)
。receiverName
获得。在其他许多编程语言中这些被隐藏起来并且通过 this
来获得接收者。Area()
方法并检查结果。CheckArea
,其参数是任何类型的几何形状。如果参数不是几何形状的类型,那么编译应该报错。 Go 语言中我们可以通过接口实现这一目的。Rectangle
和 Circle
一样创建了一个新类型,不过这次是 interface 而不是 struct。interface
的方式与大部分其他编程语言不同。通常接口定义需要这样的代码 My type Foo implements interface Bar
。Rectangle
有一个返回值类型为 float64
的方法 Area
,所以它满足接口 Shape
Circle
有一个返回值类型为 float64
的方法 Area
,所以它满足接口 Shape
string
没有这种方法,所以它不满足这个接口./shapes_test.go:25:4: undefined: Triangle
shapes_test.go:31: got 0.00 want 36.00
当测试用例不是一系列操作,而是事实的断言时,测试才清晰明了。
shapes_test.go:31: got 0.00 want 36.00
go test -run TestArea/Rectangle