Created
February 27, 2018 01:04
-
-
Save carterjones/09e8aefe690139469f84eea8ea07c91e to your computer and use it in GitHub Desktop.
a simple generic thread-safe slice type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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