Declaring empty types in go

For a given type, Data

I would like to define a set of filters, each of which handles in a Data

specific way. Some filters only need data to process, others 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 Data

. To achieve this, I defined an interface Filter

:

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

      

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

Now, let's say I have a filter that doesn't need more information. Is it useful to define it as empty struct

?

type MySimpleFilter struct {}

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

      

+3


source to share


2 answers


I would say it is good practice if you are not using a field, especially compared to another type (i.e. type MySimpleFilter int

), since an empty struct does not use a space:

https://codereview.appspot.com/4634124

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



This can also be a good idiom when using a map that you are not using for meaning (i.e. map[string]struct{}

). See this discussion for details:

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

+6


source


This is a question that has no clear answer, as it is a matter of taste. I would say this is a good practice because it makes MySimpleFilter symmetric to other filters, making the code easier to understand.



0


source







All Articles