String Interning With unique.Make

Intern equal strings with unique.Make so repeated values share one handle, cutting memory when the same keys arrive from many decoders.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"unique"
)

func main() {
	// 相同内容的字符串得到可比较的同一个 Handle
	a := unique.Make("GET")
	b := unique.Make(string([]byte{'G', 'E', 'T'}))
	fmt.Println("equal handles:", a == b)
	fmt.Println("value:", a.Value(), "| length:", len(a.Value()))

	// Handle 可比较、可作 map 键,映射开销只有一个指针
	cache := map[unique.Handle[string]]int{}
	cache[a]++
	cache[b]++
	fmt.Println("cache entries:", len(cache), "hits:", cache[a])

	// 归一化按字节精确匹配:大小写不同即不同句柄
	lower := unique.Make("get")
	fmt.Println("case sensitive:", a == lower)
	fmt.Println("distinct values:", a.Value(), lower.Value())
}

The inner workings

String Interning With unique.Make is built around the function main.

Applying it

The demo output is labeled (equal handles:, value:, cache entries:), so every line in the printed output names the step that produced it.

Statements that matter

b := unique.Make(string([]byte{'G', 'E', 'T'}))

Interactive Tools for This Topic

FAQ

What does String Interning With unique.Make print when run?
No setup needed: run the file and look for labeled lines like `equal handles:`, `value:`, `cache entries:` in the output.