在Go中声明空类型

huangapple go评论84阅读模式
英文:

declaring empty types in go

问题

对于给定的类型Data,我想定义一组过滤器,每个过滤器以某种方式处理Data。有些过滤器只需要处理数据,而其他过滤器可能需要额外的参数。

type Data struct {
    ...
}

我希望能够定义一个过滤器列表,并将它们顺序应用于Data的实例。为了实现这一点,我定义了一个Filter接口:

type Filter interface {
    Apply(d *Data) error
}

要定义一个过滤器,我只需要创建一个新类型并为其定义Apply方法。

现在,假设我有一个不需要任何额外信息的过滤器。将其定义为空的struct是一个好的做法吗?

type MySimpleFilter struct {}

func (f *MySimpleFilter) Apply(d *Data) {
    ...
}
英文:

For a given type Data , I would like to define a set of filters, each processing Data in a certain way. Some filters only need the data to be processed, other may need additional parameters.

type Data struct {
    ...
}

I want to be able to define a list of filters, and apply them sequentially to an instance of Data. To acheive this, I defined a Filter interface :

type Filter interface {
    Apply (d *Data) error
}

To define a filter, all I have to do is create a new type and define the Apply method for it.

Now, let's say I have a filter that does not need any additional information. Is it good practice to define it as an empty struct ?

type MySimpleFilter struct {}

func (f *MySimpleFilter) Apply (d *Data) {
    ...
}

答案1

得分: 7

我会争辩说,如果你对一个字段没有用处,尤其是与使用另一种类型(例如 type MySimpleFilter int)相比的话,这是一个很好的做法,因为一个空结构体不占用空间:

https://codereview.appspot.com/4634124

而且它仍然可以满足接口合约(因此在某些情况下比函数式方法更有用)。

当你使用一个对值没有用处的映射时,这也是一个很好的习惯用法(例如 map[string]struct{})。有关详细信息,请参阅以下讨论:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/lb4xLHq7wug

英文:

I'd argue this is good practice if you have no use for a Field, especially compared to using another type (i.e. type MySimpleFilter int) because an empty struct uses no space:

https://codereview.appspot.com/4634124

and it can still fulfill interface contracts (hence can be more useful than a functional approach in some cases).

This can also be a good idiom when using a map that you have no use for the value (i.e. map[string]struct{}). See this discussion for details:

https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/lb4xLHq7wug

答案2

得分: 0

这是一个没有明确答案的问题,因为这是一个品味问题。我会说这是一个好的实践,因为它使得MySimpleFilter对其他过滤器具有对称性,这使得代码更容易理解。

英文:

This is a question that doesn't have a clear answer since it's a matter of taste. I'd say it is good practice because it makes MySimpleFilter symmetrical to the other filters, which makes it easier to understand the code.

huangapple
  • 本文由 发表于 2013年1月22日 18:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/14456585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定