Imagine a Go service handling thousands of requests per second with the same tags, domains, or region codes. Keeping a million copies of "region-eu" and comparing them byte by byte wastes both RAM and CPU. Previously, teams built caches on sync.Map and struggled with evicting stale entries.
Since Go 1.23, the standard library includes the unique package for value interning: it stores one canonical copy in memory and hands back a compact unique.Handle[T]. Internally it uses a table with weak references — once no live handles remain, the garbage collector cleans up the entry.
package main
import (
"fmt"
"unique"
)
func main() {
// Store value in the table and get a handle
h1 := unique.Make("region-eu")
h2 := unique.Make("region-eu")
// Compares pointers, not string bytes
fmt.Println(h1 == h2) // true
// Retrieve a shallow copy of the value
fmt.Println(h1.Value()) // region-eu
}
Make and Value are concurrency-safe, with two caveats. First, the type must be comparable (strings, numbers, arrays, and simple structs work; slices and maps don't). Second, Value() returns a shallow copy, so never mutate data through pointers inside a struct. And don't sprinkle unique everywhere blindly: table lookups have a cost, so benchmark your real workload with go test -bench first.
