go - Go 中公共(public)接口(interface)的意义何在?

标签 go

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/

    相关文章:

    sockets - Golang tcp socket read 最终给出 EOF

    go - os.Args 只读取在 golang 中运行文件时给出的一些数据

    go - 如何查看当前本地时间是否为夏令时?

    regex - Golang 正则表达式替换不包括带引号的字符串

    go - 如何在 Golang 中将 vars 传递给 chi router

    http - golang 中的默认 HTTP 拨号超时值

    go - 调用 struct literal 的方法

    for-loop - Golang 赋值

    c - 从 Go 初始化灵活数组 C 结构成员

    json - 是否可以在Go中添加嵌套的json "as is"?