Documentation ¶
Overview ¶
Package mem implements the memory utility such as memory pool.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Pool ¶
type Pool[T any] struct { // contains filtered or unexported fields }
Pool represents memory pool of T.
It is suitable for managing temporary objects that can be individually saved and retrieved (mem.Pool.Put and mem.Pool.Get). Unlike variables or pointer variables, mem.Pool is safe for use by multiple goroutines and no new memory will be allocated.
It is a wrapper of sync.Pool to support generics and easy to use. For the actual usage, see the example in the package documentation.
Example ¶
package main import ( "fmt" "github.com/ikawaha/kagome/v2/tokenizer/lattice/mem" ) func main() { type Foo struct { Bar string } // newFoo is a constructor of Foo type. newFoo := func() *Foo { return &Foo{ Bar: "let the foo begin", } } // Create a new memory pool of Foo type. // If the memory pool is empty, it creates a new instance of Foo using newFoo. bufPool := mem.NewPool[Foo](newFoo) // Retrieve a Foo instance from the memory pool and print the current value // of the Bar field. a := bufPool.Get() fmt.Println(a.Bar) // Set the Bar field then put it back to the memory pool. a.Bar = "buz" bufPool.Put(a) // Same as above but set a different value to the Bar field. // // This will overwrite the previous value. But note that this will not allocate // new memory and is safe for use by multiple goroutines simultaneously. // See the benchmark in the same test file. b := bufPool.Get() b.Bar = "qux" bufPool.Put(b) // Retrieve a Foo instance from the memory pool and print the current value // of the Bar field. c := bufPool.Get() fmt.Println(c.Bar) }
Output: let the foo begin qux
Click to show internal directories.
Click to hide internal directories.