changwei
V2EX  ›  问与答

我一直对 Golang 的 Interface 设计感到疑惑

  •  
  •   changwei · Jun 7, 2017 · 3258 views
    This topic created in 3287 days ago, the information mentioned may be changed or developed.

    Golang 里面没有 implements 这种关键字来显式的指明某个函数是否实现了某个接口,那么意味着我如果实现函数有和接口不一致的地方,编译器不会提醒我啊。

    我觉得像 Java 里面就做得很好,接口实现要用 implements 显示说明,函数重写也有 @override 注解,基本上在编码期间靠 IDE 提示都能找出问题。

    难道是我用 Golang 的姿势不对吗?还是 Golang 本身就是这样设计的?

    (还有 Golang 接口前面要指定一个 struct,这是为了模拟出一种面向对象的编程风格吗)

    8 replies    2017-06-07 17:18:25 +08:00
    nybux
        1
    nybux  
       Jun 7, 2017
    go 不是面向对象语言,没有继承一说,你只要在类型上实现的方法和 interface 指定的一样就行了。
    这种叫“鸭子类型”
    https://zh.wikipedia.org/wiki/%E9%B8%AD%E5%AD%90%E7%B1%BB%E5%9E%8B
    cloudzhou
        2
    cloudzhou  
       Jun 7, 2017
    使用

    var _ Interfacer = (*Implementer)(nil)

    的方式进行强约束
    jarlyyn
        3
    jarlyyn  
       Jun 7, 2017
    “实现函数有和接口不一致的地方,编译器不会提醒我啊”

    在用的地方 会提醒啊。


    Golang 接口前面要指定一个 struct

    没看懂。

    不是 struct 去符合接口么?
    SuperMild
        5
    SuperMild  
       Jun 7, 2017
    一般代码不会出现接口不一致又能编译通过的情况,如果实在有需要,可以手动写些判断语句。
    另外,golang 是不是经典的面向对象,没有 class,但是有很丰富和强大、同时又简单好用的 type。

    interface 只指定 method,不指定别的了,你既可以用一个 struct 去实现,也可以用一个 function 去实现,function 也可以有自己的 method,非常好玩。
    zhs227
        6
    zhs227  
       Jun 7, 2017
    golang 的 interface 是个相当巧妙的设计,可惜了 IDE 变瞎了。
    elgoog1970
        7
    elgoog1970  
       Jun 7, 2017
    golang 主要特色:
    1. interface
    2. channel
    3. goroutine
    工程项目是少不了这个的。
    zhujinliang
        8
    zhujinliang  
       Jun 7, 2017 via iPhone
    写一个 test 就知道能不能实现了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6014 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 64ms · UTC 03:24 · PVG 11:24 · LAX 20:24 · JFK 23:24
    ♥ Do have faith in what you're doing.