1.18 sync.Pool 泛型封装

package utils

import "sync"

type Pool[T Item[T]] struct {
    p sync.Pool
}

type Default[T any] interface {
    Default() T
}

type Reset interface {
    Reset()
}

type Item[T any] interface {
    Reset
    Default[T]
}

func NewPool[T Item[T]]() *Pool[T] {
    return &Pool[T]{
        p: sync.Pool{New: func() any {
            var a T
            return a.Default()
        }},
    }
}

func (p *Pool[T]) Get() T {
    return p.p.Get().(T)
}

func (p *Pool[T]) Put(t T) {
    t.Reset()
    p.p.Put(t)
}

测试

func main() {

    p := utils.NewPool[*Node]()
    fmt.Printf("p.Get(): %v\n", p.Get())

}

type Node struct {
    a int
}

func (n *Node) Reset() {
    n.a = 99
}
func (n *Node) Default() *Node {
    fmt.Printf("n: %v\n", n) // note: n is nil
    return new(Node)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
謎麟
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!