github.com/Mericusta/go-stp@v0.6.8/pool_test.go (about) 1 package stp 2 3 import ( 4 "fmt" 5 "math" 6 "math/rand" 7 "testing" 8 ) 9 10 // 简单结构体 11 type simpleStruct struct { 12 b bool 13 v int 14 } 15 16 func (s *simpleStruct) Init() { s.b, s.v = true, math.MaxInt64 } 17 18 func (s *simpleStruct) Use() { s.b, s.v = false, rand.Intn(s.v) } 19 20 func (s *simpleStruct) Free() { s.b, s.v = false, 0 } // null method 21 22 // 内存池测试函数 23 func poolFoo(c int) { 24 // 初始化: 25 // - 需要显式传递类型参数:结构体 26 // 分配内存: 27 // - 不需要外部计算对象大小 28 // 获取对象: 29 // - 不需要外部提供数组的下标 30 // - 不需要显式传递类型参数 31 // - 不需要定义任何接口 32 pool := NewPool[simpleStruct](c) 33 fmt.Printf("pool = %v\n", pool.b) 34 35 for i := 0; i < c; i++ { 36 o := pool.Get() 37 o.Init() 38 fmt.Printf("i %v, o %v, ptr %p\n", i, o, &o) 39 o.Use() 40 fmt.Printf("i %v, o %v, ptr %p\n", i, o, &o) 41 fmt.Printf("i %v, pool = %v\n", i, pool.b) 42 } 43 } 44 45 func Test_poolFoo(t *testing.T) { 46 type args struct { 47 c int 48 } 49 tests := []struct { 50 name string 51 args args 52 }{ 53 { 54 "test case 1", 55 args{c: 2}, 56 }, 57 } 58 for _, tt := range tests { 59 t.Run(tt.name, func(t *testing.T) { 60 poolFoo(tt.args.c) 61 }) 62 } 63 }