Skip to content

Instantly share code, notes, and snippets.

@carterjones
Created February 27, 2018 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carterjones/09e8aefe690139469f84eea8ea07c91e to your computer and use it in GitHub Desktop.
Save carterjones/09e8aefe690139469f84eea8ea07c91e to your computer and use it in GitHub Desktop.
a simple generic thread-safe slice type
// Copy/paste this and replace []interface{} with whatever type you want to get
// type safety.
import (
"sync"
)
// SafeSlice is a thread-safe wrapper around an underlying slice.
type SafeSlice struct {
data []interface{}
mux sync.Mutex
}
// Append adds a value to the underlying slice.
func (s *SafeSlice) Append(v interface{}) {
s.mux.Lock()
defer s.mux.Unlock()
s.data = append(s.data, v)
}
// Len returns the length of the underlying slice.
func (s *SafeSlice) Len() int {
s.mux.Lock()
defer s.mux.Unlock()
return len(s.data)
}
// Data returns the underlying slice.
func (s *SafeSlice) Data() []interface{} {
s.mux.Lock()
defer s.mux.Unlock()
return s.data
}
// Replace replaces the underlying slice with the new slice.
func (s *SafeSlice) Replace(newSlice []interface{}) {
s.mux.Lock()
defer s.mux.Unlock()
s.data = newSlice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment