Documentation
¶
Overview ¶
Package container 提供泛型容器微件:并发安全 Map(sync.Map 背书)、 SafeMap(RWMutex)、并发安全 Slice、Set、环形缓冲 Ring、阻塞队列 Queue。 全部零依赖(仅标准库)。
设计参考 go-kratos/kit container(maps/sets/slices)与 go-zero collection 的容器件,全面泛型化并按 Go 习惯收敛语义;v0.8.0 起收编原 collectionx 全部 API(Set/Ring/Queue/SafeMap 类型名与签名不变,仅换 import 路径):
- Set / Ring 为非并发安全(单 goroutine 或外部加锁使用);
- Queue / SafeMap / Map / Slice 内建并发安全;
- Ring 溢出覆盖最旧值(有界有损),Queue 无界无损;
- Map(sync.Map 背书)适合 key 集合稳定、读多写少的场景; 写冲突频繁或需要 GetOrSet 时用 SafeMap(RWMutex 背书)。
用法:
s := container.NewSet(1, 2, 3)
s.Add(4)
q := container.NewQueue[int]()
q.Put(1)
v, ok := q.Take() // 阻塞直至有元素或关闭
m := container.NewMap[string, *User]()
m.Store("u1", u)
sl := container.NewSlice[int]()
sl.Append(1, 2, 3)
Index ¶
- type Map
- type Queue
- type Ring
- type SafeMap
- type Set
- func (s Set[T]) Add(v T)
- func (s Set[T]) AddAll(items ...T)
- func (s Set[T]) Clone() Set[T]
- func (s Set[T]) Contains(v T) bool
- func (s Set[T]) Difference(other Set[T]) Set[T]
- func (s Set[T]) Intersect(other Set[T]) Set[T]
- func (s Set[T]) Items() []T
- func (s Set[T]) Len() int
- func (s Set[T]) Range(fn func(v T) bool)
- func (s Set[T]) Remove(v T)
- func (s Set[T]) Union(other Set[T]) Set[T]
- type Slice
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 { // contains filtered or unexported fields }
Map 并发安全的泛型映射(sync.Map 背书,对标 go-kratos/kit container/maps)。 读多写少、key 集合趋于稳定时性能优于 SafeMap;写冲突频繁或需要 GetOrSet 语义时用 SafeMap。零值不可直接使用,须经 NewMap 创建。
func (*Map[K, V]) LoadOrStore ¶
LoadOrStore 原子地"不存在则写入":返回当前值与是否本已存在。
type Queue ¶
type Queue[T any] struct { // contains filtered or unexported fields }
Queue 无界阻塞 FIFO 队列(并发安全):多生产者/多消费者, Take 阻塞直至有元素或队列关闭。Close 后 Put 直接 panic(与 向已关闭 channel 发送的语义一致)。
func (*Queue[T]) Close ¶
func (q *Queue[T]) Close()
Close 关闭队列:唤醒全部阻塞的 Take(取完余量后返回 false); 幂等。关闭后 Put 会 panic。
type Ring ¶
type Ring[T any] struct { // contains filtered or unexported fields }
Ring 定长环形缓冲(非并发安全):生产快于消费最多保留最新 n 个元素, 超出后 Add 覆盖最旧值且保序 FIFO(有界有损,适合"只要最新 n 条"的场景, 如最近请求采样、滑动日志)。
type SafeMap ¶
type SafeMap[K comparable, V any] struct { // contains filtered or unexported fields }
SafeMap 并发安全的泛型映射(RWMutex 保护),对标 go-zero collection/SafeMap 的泛型化替代。零值不可直接使用,须经 NewSafeMap 创建。
type Set ¶
type Set[T comparable] map[T]struct{}
Set 泛型集合(非并发安全:单 goroutine 使用,或由调用方加锁保护)。
func (Set[T]) Difference ¶
Difference 差集:返回存在于 s 但不存在于 other 的新集合。
type Slice ¶
type Slice[T any] struct { // contains filtered or unexported fields }
Slice 并发安全的泛型切片(RWMutex 保护,对标 go-kratos/kit container/slices)。 零值不可直接使用,须经 NewSlice 创建。