dsdt66064367 2018-08-30 03:16
浏览 95
已采纳

Golang OOP澄清

I have two interfaces written in go, one which is a subset of the other

type x interface {
    a()
}

type y interface {
    a()
    b()
}

I also have a struct that has methods as such

type z struct {
    some string
}

func (s z) a() {
    // do stuff
}

func (s z) b() {
    // do stuff
}

I have a few questions regarding this, namely:

  1. Am I right to say that z implements both x and y?
  2. What is the OOP concept for one struct implementing multiple interfaces in this way?

I tried asking a few colleagues, who seem to lean towards polymorphism as the answer although they are not too sure. The wikipedia entry for polymorphism says that it "is the provision of a single interface to entities of different types", but this feels like the direct reverse to me. I have also found in other sources (eg. this) that Go is "not really a OOP language".

  • 写回答

3条回答 默认 最新

  • douzhuan0309 2018-08-30 04:27
    关注

    Yes, z implements both x and y. You can prove that by using a variable declaration to assign a concrete type to an interface type:

    var _ x = z{}
    var _ y = z{}
    

    That gives you a compile time check to ensure that a type implements the interfaces you want it to.

    As a side note, if you explicitly wanted y to be x + some more methods, then it'd make sense to write it like this:

    interface y {
        x
        b()
    }
    

    About the naming, if a type implements two different interfaces which share some methods, I'd call it just that - a type that's implementing two different interfaces. One interface being a subset of another doesn't matter.

    Moreover in Go, types (non struct types as well) are not associated with interfaces when they are defined. Even if a type was not written to implement some interface, you can make it implement any number of interfaces by defining new interfaces with different names and/or different combinations of methods from the type. That makes giving a name to the concept even harder - how would you know the name at the time of type definition when interfaces may be defined later in another package?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1