简体   繁体   中英

declaring empty types in go

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

I'd argue this is good practice if you have no use for a Field, especially compared to using another type (ie 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 (ie map[string]struct{} ). See this discussion for details:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM