Intern Strings With unique.Make

Canonicalize repeated strings through unique.Make so equal values share one handle, cutting duplicate allocations in hot paths.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"unique"
)

func main() {
	labels := []string{"prod", "prod", "staging", "prod", "staging"}

	// unique.Make 对相同内容返回相同 Handle,内部去重
	handles := make([]unique.Handle[string], 0, len(labels))
	for _, l := range labels {
		handles = append(handles, unique.Make(l))
	}

	fmt.Println("prod==prod handles:", handles[0] == handles[1])
	fmt.Println("prod==staging handles:", handles[0] == handles[2])

	// Value() 取回原字符串
	fmt.Println("recovered:", handles[3].Value())

	// 相同内容只保留一份:这里两次 Make 指向同一 Interned 值
	a := unique.Make("region-eu")
	b := unique.Make("region-eu")
	fmt.Println("interned once:", a == b)
}

What the code does

A natural reading: the function main, doing all the work.

The file repeats itself only inside for _, l := range labels.

What to watch for

  • The runtime is the only requirement — no packages, no install.

Applying it

The run emits 4 labeled sections — prod==prod handles:, prod==staging handles:, recovered:, interned once: — one per step.

Statements that matter

for _, l := range labels {
	handles = append(handles, unique.Make(l))
}
handles := make([]unique.Handle[string], 0, len(labels))

Interactive Tools for This Topic

FAQ

What does Intern Strings With unique.Make print when run?
The script runs standalone; its 4 labeled outputs include `prod==prod handles:`, `prod==staging handles:`, `recovered:`.