Go标准库定义的接口:源码位置:src/builtin/builtin.go// The error built-in interface type is the conventional interface for // representing an error condition, with the nil value representing no error. type error interface { Error() string }源码位置:src/io/io.gotype Reader interface { Read(p []byte) (n int, err error) }源码位置:src/net/http/server.gotype ResponseWriter interface { Header() Header Write([]byte) (int, error) WriteHeader(statusCode int) }可以看到上面的接口的方法数量为1~3个这种小接口的最佳实践已经被Go程序员和各个社区项目广泛采用.
小接口的优势:
.接口越小.抽象程度越高.被接纳度越高.计算机程序本身就是对真实世界的抽象与在构建.抽象是对同类事物去除其个别的 次要的方面.抽取其相同的 主要的方面的方法.不同的抽象程度会导致抽象出的概念对应的事物集合不同.抽象程度越高.对应的空间集合越大.抽象程度越低(越具象.越接近事物的真实面貌).对应的空间集合越小.示例:// 会飞的. type Flyable interface { Fly() } // 会游泳的. type Swimmable interface { Swim() } // 会飞会游泳的. type FlySwimmable interface { FlySwim() }