← 返回 Golang 列表

Go 接口与多态设计

隐式接口满足, duck typing 在 Go 中的体现与最佳实践。

隐式接口满足

Go 中类型不需要显式声明实现接口,只要方法集匹配即可。

type Reader interface {
  Read(p []byte) (n int, err error)
}

type File struct{}
func (f File) Read(p []byte) (n int, err error) { return }

接口设计原则