douzheng0702 2019-09-13 11:06
浏览 105
已采纳

为什么我们在Go的界面中不能拥有属性? [关闭]

I understand you cannot do it, and understand how interfaces work in Go. But my main concern is why it was decided interfaces could not declare fields.

I can see even a proposal to add it to Go V2.

Can someone give a clear explanation about this?

  • 写回答

1条回答 默认 最新

  • douba1498 2019-09-13 12:17
    关注

    One reason, as Volker so accurately puts it in the comment he left: "Interfaces encapsulate behavior only. Data is not behavior."

    Another, far more easy to understand reason would be: testing. Currently, an interface only specifies a set of behaviours. Suppose I've got some code I want to test that expects a Writer interface. If some ham-fisted dev implemented an interface like this:

    type Writer interface {
        F *os.File
        Write(b []bytes) (int, error)
    }
    

    Then I'd need a mock type that has a file pointer (which I might not be able to leave at nil, because the interface should be usable by the code I call). That's horrible in and of itself. Of course, creating a temp file is easy.

    Now how about an interface like this:

    type ComplexInterface interface {
       Engine *mypkg.SomeComplexType
       Client *grpc.Client
       // and so on
    }
    

    I'd need to create a complex type instance, which in turn might have 20 dependencies... God only knows how expensive a change to any of the interfaces might become. If mypkg.SomeComplexType changes, then I'd soon find out that tests in another package start breaking, because I've created a very tight coupling.

    So yeah: interfaces define behaviour, adding properties introduces a ton of risks (interfaces as pseudo-generics, tight coupling, maintenance hell, ...)

    Either way, if you want "properties" in an interface, why not simply write this:

    type MyWriter interface {
        File() *os.File
        Write(b []bytes) (int, error)
    }
    

    Substitute a property for a getter. Job done.

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

报告相同问题?

悬赏问题

  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果