Receiving Slices and Maps
Remember that when a map or a slice is passed as a function parameter, if you store a reference to them, users can modify them.
Non-recommended approach:
func (d *Driver) SetTrips(trips []Trip) {
d.trips = trips
}
trips := ...
d1.SetTrips(trips)
// Are you trying to modify d1.trips?
trips[0] = ...
Recommended approach:
func (d *Driver) SetTrips(trips []Trip) {
d.trips = make([]Trip, len(trips))
copy(d.trips, trips)
}
trips := ...
d1.SetTrips(trips)
// Here we modify trips[0], but it won't affect d1.trips
trips[0] = ...
Returning Slices or Maps
Similarly, be mindful of users modifying a map or slice that exposes internal state.
Non-recommended approach:
type Stats struct {
mu sync.Mutex
counters map[string]int
}
// Snapshot returns the current state
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
return s.counters
}
// snapshot is no longer protected by the mutex
// so any access to snapshot will be subject to data race and affect stats.counters
snapshot := stats.Snapshot()
Recommended approach:
type Stats struct {
mu sync.Mutex
counters map[string]int
}
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
result := make(map[string]int, len(s.counters))
for k, v := range s.counters {
result[k] = v
}
return result
}
// snapshot is now a copy
snapshot := stats.Snapshot()