教程“Interfaces in Go - Part 2: Aiding adaptable, evolutionary design ”(2012 年 1 月,来自 Sathish VJ)清楚地提到了 Go 中接口的主要优势:
Go 的接口不是 Java 或 C# 接口的变体,它们更多。
它们是大规模编程和适应性进化设计的关键。
请参阅同一篇文章中关于总线的不同视角(接口)的这个示例:
package main
import "fmt"
//Go Step 1: Define your data structures
type Bus struct {
l, b, h int
rows, seatsPerRow int
}
//Go Step 2: Define a real world abstraction that could use the data we structure we have
type Cuboider interface {
CubicVolume() int
}
//Go Step 3: Implement methods to work on data
func (bus Bus) CubicVolume() int {
return bus.l * bus.b * bus.h
}
//Go step - repeat 2 & 3 for any other interfaces
type PublicTransporter interface {
PassengerCapacity() int
}
func (bus Bus) PassengerCapacity() int {
return bus.rows * bus.seatsPerRow
}
func main() {
b := Bus{
l:10, b:6, h:3,
rows:10, seatsPerRow:5}
fmt.Println("Cubic volume of bus:", b.CubicVolume())
fmt.Println("Maximum number of passengers:", b.PassengerCapacity())
}
它似乎以数据为中心 - 首先定义您的数据,并在您进行时构建您的接口抽象。
这里的层次结构是“沿途”构建的,没有明确说明 - 根据与类型关联的方法签名,它被理解为实现特定的接口。
现在让我们假设随着时间的推移,我们的巴士的一些项目要求发生了变化 - 现在有一项新法律规定每位乘客至少应有一定的最小立方体积。
我们的总线现在必须遵守一个名为 PersonalSpaceLaw 的新接口,它不同于它已经实现的任何其他接口
//new requirement that the Bus must be compatible with
type PersonalSpaceLaw interface {
IsCompliantWithLaw() bool
}
func (b Bus) IsCompliantWithLaw() bool {
return (b.l * b.b * b.h) / (b.rows * b.seatsPerRow) >= 3
}
功能已被扩展,核心类或核心层次结构没有任何变化。这种实现更加简洁、易于扩展,并且可以随着项目需求的不断变化而更好地扩展。
这里是full working program in Go Playground
文章以 John Asmuth 引用的关于 Go 中接口的生产力的帖子结尾:
“事实上,我不必花时间预先设计某种类型层次结构,然后在完成之前重新排列它两到三遍。
这甚至不是很容易做到正确的事实 -
事实上我只是不必担心它并且可以继续使用实际的算法。“