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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制