← 中文资源

简体中文版本

按投影键去重保留首次出现

按投影键(小写化邮箱)去重记录:保留每个键的首次出现,整值相等才判重的粗粒度去重在这里不够用,结构体记录去重正是如此,大小写不同也算重复。投影函数由调用方以闭包注入,这里用 strings.ToLower(r.Email),seen map 命中即跳过,out 容量按记录数预分配。

阅读英文原文

实现说明

按投影键去重保留首次出现的核心是函数 uniqueByKey、main。 循环只出现在 for _, r := range records,它的每次迭代处理一个元素。

使用要点

  • 直接运行文件,输出会带上标签,比如 kept——输出的每一行都能指回产生它的那次调用。
  • main 的演示流程是 uniqueByKey——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「按投影键去重保留首次出现」会打印什么?

运行文件本身,kept 这些前缀各对应一段演示逻辑。

入口签名:func uniqueByKey(records []Record, key func(Record) string) []Record

核心语句

for _, r := range records {
	k := key(r)
	if seen[k] {
		continue
	}
	seen[k] = true
	out = append(out, r)
}
for _, r := range unique {
	fmt.Println(r.Email, "->", r.Role)
}
seen := make(map[string]bool, len(records))

代码示例

package main

import (
	"fmt"
	"strings"
)

type Record struct {
	Email string
	Role  string
}

// uniqueByKey keeps the first record for each projected key (lowercased email).
func uniqueByKey(records []Record, key func(Record) string) []Record {
	seen := make(map[string]bool, len(records))
	out := make([]Record, 0, len(records))
	for _, r := range records {
		k := key(r)
		if seen[k] {
			continue
		}
		seen[k] = true
		out = append(out, r)
	}
	return out
}

func main() {
	records := []Record{
		{"[email protected]", "admin"},
		{"[email protected]", "editor"},
		{"[email protected]", "viewer"},
		{"[email protected]", "auditor"},
		{"[email protected]", "viewer"},
	}

	unique := uniqueByKey(records, func(r Record) string {
		return strings.ToLower(r.Email)
	})

	fmt.Println("kept", len(unique), "of", len(records), "records")
	for _, r := range unique {
		fmt.Println(r.Email, "->", r.Role)
	}
}