Slices, Maps

Slices and maps contain pointers to the underlying data so be wary of scenarios when they need to be copied.

Declaring Empty Slices

When declaring an empty slice, prefer

var t []string

over

t := []string{}

The former declares a nil slice value, while the latter is non-nil but zero-length. They are functionally equivalent—their len and cap are both zero—but the nil slice is the preferred style.

Copying Slices and Maps

Keep in mind that users can modify a map or slice you received as an argument if you store a reference to it.

// BAD
func (d *Driver) SetTrips(trips []Trip) {
  d.trips = trips
}

trips := ...
d1.SetTrips(trips)

// Did you mean to modify d1.trips?
trips[0] = ...

Returning Slices and Maps

Similarly, be wary of user modifications to maps or slices exposing internal state.

Slice

Map

Don't create new variables with append

Last updated

Was this helpful?