Paul Di Gian
Paul Di Gian's Blog

Paul Di Gian's Blog

Advanced go - Use default value as your advantage, append to nil

Paul Di Gian's photo
Paul Di Gian
·Nov 3, 2021·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Today I found a small mistake in our codebase.

The code was like this:

type Foo struct {
    baz []int
}

// ...

func (f *Foo) Fun(a int) {
    if len(f.baz) == 0 {
        f.baz = []int{a}
    } else {
        f.baz = append(f.baz, a)
    }
}

Which is not wrong, but it could be improved.

Appending to a nil slice will work just as well.

The code could be simplified like:

func (f *Foo) Fun(a int) {
    f.baz = append(f.baz, a)
}

This code, not only works, but it is more idiomatic.

Fewer branches and a cleaner control flow.

Whenever possible in go, we should exploit defaults value.

 
Share this