enumcache

enumcache provides thread-safe storage and lookup for enumeration name and ID mappings.

Part of nurago, a collection of independent Go packages for backend services.

import "github.com/tecnickcom/nurago/pkg/enumcache"

Package enumcache provides thread-safe storage and lookup for enumeration name and ID mappings.

It maps string names to integer IDs and back, and supports encoding and decoding enum bitmaps when enum IDs represent bit flags.

Typical usage is set-once, read-many: populate entries during startup using Set, SetAllIDByName, or SetAllNameByID, then perform lookups from application code.

When To Use

  • Reference data maps small integer IDs to names and both directions are queried.
  • The set is loaded at startup and read constantly afterwards.

Example

// create a new cache
ec := enumcache.New()

// add an entry
ec.Set(1, "alpha")

// get the numerical ID associated to a string
id, err := ec.ID("alpha")
if err != nil {
	log.Fatal(err)
}

fmt.Println(id)

// get the string name associated to a numerical ID
name, err := ec.Name(1)
if err != nil {
	log.Fatal(err)
}

fmt.Println(name)

// Output:
// 1
// alpha

Full source is in example_enumcache_test.go. More runnable examples are on pkg.go.dev.

Dependencies

This package reaches no external module: it uses only the Go standard library.