我正在学习 Go 并试图完全理解如何在 Go 中使用接口。
在 The Way to Go 一书中,有一个示例清单 11.1(第 264-265 页)。我觉得我对它的理解肯定缺少一些东西。代码运行良好,但我不明白接口对结构和方法有什么影响(如果有的话)。
package main
import "fmt"
type Shaper interface {
Area() float32
}
type Square struct {
side float32
}
func (sq *Square) Area() float32 {
return sq.side * sq.side
}
func main() {
sq1 := new(Square)
sq1.side = 5
// var areaIntf Shaper
// areaIntf = sq1
// shorter, without separate declaration:
// areaIntf := Shaper(sq1)
// or even:
areaIntf := sq1
fmt.Printf("The square has area: %f\n", areaIntf.Area())
}
Helenr
相关分类