gitee.com/quant1x/gox@v1.21.2/cache/pool.go (about) 1 package cache 2 3 import "sync" 4 5 // Pool 二次封装的泛型sync.Pool 6 type Pool[E any] struct { 7 once sync.Once // 初始化sync.Pool的New接口 8 pool sync.Pool // sync.Pool 9 zero E // 零值 10 } 11 12 // 初始化sync.Pool.New 13 func (this *Pool[E]) init() { 14 this.pool = sync.Pool{New: func() any { 15 var e E 16 return &e 17 }} 18 } 19 20 // Acquire 申请内存 21 func (this *Pool[E]) Acquire() *E { 22 this.once.Do(this.init) 23 obj := this.pool.Get().(*E) 24 *obj = this.zero 25 return obj 26 } 27 28 // Release 释放内存 29 func (this *Pool[E]) Release(obj *E) { 30 this.once.Do(this.init) 31 if obj == nil { 32 return 33 } 34 this.pool.Put(obj) 35 }