← 中文资源

简体中文版本

用 unique.Make 驻留字符串

通过 unique.Make 把重复字符串规范化为同一 Handle:相等内容共享一份、== 可直接比较,Value() 取回原值,热路径省内存。

阅读英文原文

实现说明

用 unique.Make 驻留字符串以函数 main为骨架。 for _, l := range labels 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 每一步打印都带着自己的标签:prod==prod handles:、prod==staging handles:、recovered:。

常见问题

运行「用 unique.Make 驻留字符串」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 prod==prod handles:、prod==staging handles:、recovered: 标签标明各步骤。

核心语句

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

代码示例

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)
}