package test import ( "fmt" "sync" "testing" ) func TestSync(t *testing.T) { // 创建一个对象池,New 是当对象池为空时提供的对象 pool := sync.Pool{ New: func() interface{} { fmt.Println("Creating a new instance.") return "New Object" }, } // 从池中获取对象 obj1 := pool.Get().(string) fmt.Println("Got:", obj1) // 放回对象池 pool.Put("Reused Object") // 再次从池中获取对象,这次会使用池中已有的对象 obj2 := pool.Get().(string) fmt.Println("Got:", obj2) // 第三次从池中获取对象,池已为空,会调用 New 函数创建新对象 obj3 := pool.Get().(string) fmt.Println("Got:", obj3) }