为什么我们不能在Go的界面中拥有属性? [英] Why can't we have properties in Go's interfaces?

查看:81
本文介绍了为什么我们不能在Go的界面中拥有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解您无法做到,并且了解接口在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.

我什至可以看到将其添加到Go V2中的提案.

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

有人可以对此给出清晰的解释吗?

Can someone give a clear explanation about this?

推荐答案

一个原因,因为沃尔克(Volker)如此准确地将其放在注释中:接口仅封装行为.数据不是行为."

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

另一个更容易理解的原因是:测试.当前,接口仅指定一组行为.假设我要测试一些需要Writer接口的代码.如果有些脚的开发人员实现了这样的接口:

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)
}

然后,我需要一个具有文件指针的模拟类型(由于接口应该可以被我调用的代码使用,所以我可能无法将其保留在nil处).这本身就是可怕的.当然,创建临时文件很容易.

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
}

我需要创建一个复杂的类型实例,而该实例又可能具有20个依赖关系……上帝只知道对任何接口进行更改的代价可能是多么昂贵.如果mypkg.SomeComplexType发生变化,那么我很快就会发现另一个包中的测试开始中断,因为我已经创建了非常紧密的耦合.

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.

这篇关于为什么我们不能在Go的界面中拥有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆