英文:
Go interface for set of constraints and inheritance
问题
我还在努力理解Golang的接口。请纠正我并帮助我理解。
Frances Campoy解释说,interface
是一组约束条件。
所以在我的情况下,假设我有一个Store
接口,它需要与约束一起使用,就像Go中的Interface
排序一样。
type Store interface {
Earning() int
Expense() int
}
那么如果我想将这个接口约束实现到其他包中,比如StoreA
、StoreB
,我需要做什么呢?当我尝试以下代码时,我希望得到一条错误信息:
aa := StoreC{}
aa.Add("AAA")
// 错误提示:`StoreC`未实现`Add`方法,受`Store`接口约束...一些内容
那么如果我想在其他Store
中强制执行这个约束,我该怎么做?我需要像继承一样做些什么吗?
type StoreC interface {
Store
}
换句话说,我想知道如何将package sort
的三个方法的接口约束强制应用到Go中的每个sort
操作。它是如何对任何其他可能的sort
用法强制执行约束的?
谢谢!
英文:
I am still trying to understand Golang interface. Please correct me and help me understand.
Frances Campoy explains, interface
is a set of contraints.
So in my case, let's say I have one Store
interface that is to be interfaced with contrains, like sort Interface
in Go.
type Store interface {
Earning() int
Expense() int
}
Then what do I have to do if I want to implement this interface constraint to other packages like StoreA
, StoreB
? I want to get a message like when I try:
aa := StoreC{}
aa.Add("AAA")
// error saying `StoreC` does not implement method `Add`, constrained by interface `Store`... something
So what do I do if I want to enforce this contraint in other Store
s? Do I need to do something like inheritance?
type StoreC interface {
Store
}
In other words, I wonder how package sort
's interface of 3 methods can be enforced to every sort
operations in Go. How does it enforce the contraints to any other possible sort
uses in Go?
Thanks!
答案1
得分: 1
接口对于接口的使用者来说非常有用。通过查看接口提供的方法,您可以知道可以安全使用哪些方法。
如果您有一个接口:
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
的类型都将满足该接口。编译器将在编译时进行此检查。
定义一个方法大致如下:
func (receiver a_type) methodname (可能还有更多参数) 可能的返回类型 {...}
接收器的类型是定义该方法的类型。方法的名称位于接收器类型之间,然后是(可能为空的)参数列表。
英文:
An interface is mostly useful for a user of the interface. By looking at what methods the interface provides, you know what methods you can safely use.
If you have an interface:
type MyInterface interface {
Frob(int)
Flanged() bool
}
You know that any function func foo(thing MyInterface)
can safely call thing.Frob(..)
and thing.Flanged()
safely.
Any type that implements both a func (r a_type) Frob(int)
and func (r a_type) Flanged() bool
will satisfy the interface. The compiler will do this check at compile-time.
Defining a method looks (roughly) like this:
func (reciever a_type) methodname (possibly more args here) possibly_a_return_type {...}
The receiver's type is the type for which the method is defined. The name of the method comes between and then there's the (possibly empty) argument list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论