添加了getName()
函數的典型示例。如何在下面乾燥?
我不知道怎麼能不寫getName()
爲circle
和rect
兩次?
package main
import "fmt"
import "math"
// Here's a basic interface for geometric shapes.
type geometry interface {
area() float64
perim() float64
getName() string
}
// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
width, height float64
name string
}
type circle struct {
radius float64
name string
}
// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (r rect) getName() string {
return r.name
}
// The implementation for `circle`s.
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func (c circle) getName() string {
return c.name
}
// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
fmt.Println(g.getName())
}
func main() {
r := rect{width: 3, height: 4, name: "rect5"}
c := circle{radius: 5, name: "circle2"}
// The `circle` and `rect` struct types both
// implement the `geometry` interface so we can use
// instances of
// these structs as arguments to `measure`.
measure(r)
measure(c)
}
不,你不能,因爲類型'geometry'是一個接口,因此沒有暴露字段,只暴露方法。 – Adrian
您需要爲每種類型定義方法以滿足接口。你不能讓這個方法比'return c.name'更簡單,所以沒有任何功能去重複數據。 – JimB
@Adrian哎呀,我的錯! –