1.18 sync.Pool 泛型封装

Golang
410
0
0
2022-11-09
标签   Golang基础
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)
}