实现说明
按投影键去重保留首次出现的核心是函数 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)
}
}