https://github.com/golang/go/wiki/CodeReviewComments#interfaces说:
Go 接口(interface)通常属于使用接口(interface)类型值的包,而不是实现这些值的包
那么,大多数接口(interface)不能是私有(private)的吗?
package mypackage
type thinger interface {
Thing() bool
}
func Smth(t thinger) bool {...}
package otherpackage
type MyThing struct{}
func (t MyThing) Thing() bool {return true}
myVar := MyThing{}
mypackage.Smth(myVar)
公共(public)接口(interface)有什么意义?例如有什么好处?
io.Reader
作为公共(public)接口(interface)?
最佳答案
接口(interface)也是契约。以 io.Reader
例如;它具有所有实现必须遵守的特定行为,并将其用作参数或返回类型记录您期望的行为以及方法签名。反之亦然,对于具有重叠方法集的类型,如果您碰巧有相同的方法但不遵循特定的接口(interface),则可以使用不同的接口(interface)名称来区分两者(这可能不是代码库中的良好模式,但通常会遇到可能需要区分的外部接口(interface))。
当您使用 io.Reader
定义某种方法或函数时,您可以依赖 io.Reader
的所有记录行为无需每次都在您自己的代码中记录它。
Go 类型不是变体,因此您不能声明一个函数签名来满足另一个具有私有(private)接口(interface)的函数签名。如果有函数func ReadFrom(r internal)
,您无法用自己的 func ReadFrom(r myInternal)
满足该函数签名.标准库中有很多这样的例子,如果接口(interface)是私有(private)的,你就无法实现;例如
io.ReaderFrom
io.WriterTo
net.Listener
net.Conn
http.Handler
http.handlerFunc
最后,众所周知的接口(interface)也有助于简单地阅读和理解代码。
io.Reader
是一个已知的接口(interface),在源代码中很容易识别。当遇到myReader
,你不知道预期的行为是什么,甚至不知道方法集是什么,没有查阅文档。
关于go - Go 中公共(public)接口(interface)的意义何在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741482/