Unique By Key Keeps First Occurrence

Deduplicate records by a projected key — lowercased email — keeping each first occurrence instead of requiring exact whole-value equality.

GoData Integrity

Code

gosnippet
45 lines
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)
	}
}

The code at a glance — Unique By Key Keeps First Occurrence

Reading it top to bottom: the functions uniqueByKey and main, doing all the work.

A single loop drives the file — for _, r := range records.

What to watch for

  • Having the runtime installed is the whole checklist — nothing more.

Applying it

The entry-point signature is func uniqueByKey(records []Record, key func(Record) string) []Record

Look for these output labels: kept — when the file runs.

Launch the file; main takes over and steps through uniqueByKey.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Unique By Key Keeps First Occurrence print when run?
Invoke the file as-is — the `kept` prefixes identify which step printed each line.