duangang79177 2014-11-23 17:02
浏览 4
已采纳

Go接口用于一组约束和继承

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 Stores? 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条回答 默认 最新

  • duanqiang7631 2014-11-23 18:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程