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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.