README
¶
gosafe
Store values in a thread-safe way. Supports arbitrary values, slices and maps. Uses generics which means that go 1.18+ is required.
Example
package main
import (
"github.com/janitorjeff/gosafe"
)
func main() {
m := gosafe.Map[int, string]{} // equivalent to map[int]string
m.Set(123, "abc") // m[123] = "abc"
n, ok := m.Get(123) // n, ok := m[123]
// ...
}
Alongside the thread-safe methods unsafe ones are provided which allow for easy extension.
package main
import (
"github.com/janitorjeff/gosafe"
)
type CustomSlice struct {
gosafe.Slice[string]
}
func NewSlice() CustomSlice {
return CustomSlice{gosafe.Slice[string]{}}
}
func (s *CustomSlice) ChangeElemsWithLengthGreaterThanThree() {
// make it thread safe
s.Lock()
defer s.Unlock()
// use unsafe methods to avoid mutex deadlock
for i := 0; i < s.LenUnsafe(); i++ {
if len(s.GetUnsafe(i)) > 3 {
s.SetUnsafe(i, "changed")
}
}
}
func main() {
s := NewSlice()
s.Append("abc", "def", "long-string", "xyz")
s.ChangeElemsWithLengthGreaterThanThree()
print(s.Get(0), "\n") // abc
print(s.Get(2)) // changed
}
Documentation
¶
Index ¶
- type Map
- type Slice
- func (s *Slice[T]) Append(elems ...T)
- func (s *Slice[T]) AppendUnsafe(elems ...T)
- func (s *Slice[T]) DeleteStable(i int)
- func (s *Slice[T]) DeleteStableUnsafe(i int)
- func (s *Slice[T]) DeleteUnstable(i int)
- func (s *Slice[T]) DeleteUnstableUnsafe(i int)
- func (s *Slice[T]) Get(i int) T
- func (s *Slice[T]) GetUnsafe(i int) T
- func (s *Slice[T]) In(elem T) bool
- func (s *Slice[T]) InUnsafe(elem T) bool
- func (s *Slice[T]) Len() int
- func (s *Slice[T]) LenUnsafe() int
- func (s *Slice[T]) Set(i int, value T)
- func (s *Slice[T]) SetUnsafe(i int, value T)
- type Value
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Map ¶
type Map[K comparable, V any] struct { sync.RWMutex // contains filtered or unexported fields }
func (*Map[K, V]) DeleteUnsafe ¶
func (m *Map[K, V]) DeleteUnsafe(key K)
type Slice ¶
type Slice[T comparable] struct { sync.RWMutex // contains filtered or unexported fields }
func (*Slice[T]) AppendUnsafe ¶
func (s *Slice[T]) AppendUnsafe(elems ...T)
func (*Slice[T]) DeleteUnstableUnsafe ¶
Doesn't preserve order
Click to show internal directories.
Click to hide internal directories.