Intern Strings With unique.Make
Canonicalize repeated strings through unique.Make so equal values share one handle, cutting duplicate allocations in hot paths.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.