https://github.com/xgfone/go-pools
A collection of some pools, such as BufferPool, BytesPool and TaskPool.
https://github.com/xgfone/go-pools
go go-pool go-pools golang object object-pool pool pools
Last synced: 7 months ago
JSON representation
A collection of some pools, such as BufferPool, BytesPool and TaskPool.
- Host: GitHub
- URL: https://github.com/xgfone/go-pools
- Owner: xgfone
- License: apache-2.0
- Created: 2020-01-24T13:03:27.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2024-08-20T15:14:57.000Z (over 1 year ago)
- Last Synced: 2024-10-30T20:49:10.248Z (over 1 year ago)
- Topics: go, go-pool, go-pools, golang, object, object-pool, pool, pools
- Language: Go
- Homepage:
- Size: 43.9 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-pools [](https://github.com/xgfone/go-pools/actions/workflows/go.yml) [](https://pkg.go.dev/github.com/xgfone/go-pools) [](https://raw.githubusercontent.com/xgfone/go-pools/master/LICENSE)
Provide an object pool based on the generics supporting `Go1.18+`, such as `Pool`, `CapPool`.
## Install
```shell
$ go get -u github.com/xgfone/go-pools
```
## Example
#### `Pool`
```go
type Context struct {
// ....
}
pool := New(func() *Context { return new(Context) })
// Get the context from the pool.
ctx := pool.Get()
// Use the object as *Context to do something.
fmt.Println(ctx.Object) // ctx.Object => *Context
// ...
// Release the context into the pool.
ctx.Release()
// Output:
// &{}
```
#### `CapPool`
```go
// For *bytes.Buffer
bufferPool := NewCapPool(
func(cap int) *bytes.Buffer { return bytes.NewBuffer(make([]byte, 0, cap)) }, // new
func(buf *bytes.Buffer) *bytes.Buffer { buf.Reset(); return buf }, // reset
)
buffer := bufferPool.Get(1024)
// TODO ...
buffer.Release()
// For a slice, such as []byte or []interface{}
slicePool := NewCapPool(
func(cap int) []byte { return make([]byte, 0, cap) }, // new
func(buf []byte) []byte { return buf[:0] }, // reset
)
bytes := slicePool.Get(128)
// TODO ...
bytes.Release()
```