inheritance - 用于约束和继承集的接口(interface)

标签 inheritance interface go

我仍在努力理解 Golang 接口(interface)。请纠正我并帮助我理解。

Frances Campoy 解释说,interface 是一组约束。

所以在我的例子中,假设我有一个 Store 接口(interface),它要与约束接口(interface),比如 Go 中的 sort Interface

type Store interface {
    Earning() int
    Expense() int
}

那么如果我想对StoreAStoreB等其他包实现这个接口(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/

相关文章:

go - 是否可以在 Go 中定义匿名接口(interface)实现?

java - 如何避免使用instanceof/这里如何使用多态

java - 如何在没有任何关联实例的情况下调用构造函数?

iphone - Objective C 中的继承问题

python - 这个接口(interface)语法在python中是什么意思?

java - 在java中组合2个对象

go - 为什么你不能在 Go "init"中命名一个函数?

go - 使用 Golang 解决没有泛型的类型断言?

go - termui 的 termui.Handle ("/timer/1s",func(e termui.Event)) 在 ubuntu 18.04 上不工作

java - 使用抽象clone()方法克隆父类(super class)