我仍在努力理解 Golang 接口(interface)。请纠正我并帮助我理解。
Frances Campoy 解释说,interface
是一组约束。
所以在我的例子中,假设我有一个 Store
接口(interface),它要与约束接口(interface),比如 Go 中的 sort Interface
。
type Store interface {
Earning() int
Expense() int
}
那么如果我想对StoreA
、StoreB
等其他包实现这个接口(interface)约束怎么办?我想在尝试时收到一条消息:
aa := StoreC{}
aa.Add("AAA")
// error saying `StoreC` does not implement method `Add`, constrained by interface `Store`... something
那么,如果我想在其他 Store
中强制执行此约束,我该怎么办?我需要做一些类似继承的事情吗?
type StoreC interface {
Store
}
换句话说,我想知道 package sort
的 3 种方法接口(interface)如何可以强制执行到 Go 中的每个 sort
操作。它如何对 Go 中任何其他可能的 sort
使用实现约束?</p>
谢谢!
最佳答案
界面主要对界面的用户有用。通过查看接口(interface)提供了哪些方法,您就知道可以安全使用哪些方法。
如果你有一个接口(interface):
type MyInterface interface {
Frob(int)
Flanged() bool
}
你知道任何函数 func foo(thing MyInterface)
都可以安全地调用 thing.Frob(..)
和 thing.Flanged()
安全地。
任何同时实现func (r a_type) Frob(int)
和func (r a_type) Flanged() bool
的类型都将满足该接口(interface)。编译器将在编译时进行此检查。
定义一个方法看起来(大致)像这样:
func (reciever a_type) methodname (possibly more args here) possibly_a_return_type {...}
接收者的类型是为其定义方法的类型。方法的名称介于两者之间,然后是(可能为空的)参数列表。
关于inheritance - 用于约束和继承集的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091688/