How to remove duplicates from a slice in Go and keep its order
To remove duplicates from a Go slice while keeping the first occurrence, iterate over the input and use a map to remember values you have seen. Append a value to the result the first time you encounter it. Reading the input in order gives you a stable result even though Go map iteration order is unspecified.
Keep the first occurrence
package main
import "fmt"
func Unique[T comparable](values []T) []T {
seen := make(map[T]struct{})
var result []T
for _, value := range values {
if _, exists := seen[value]; exists {
continue
}
seen[value] = struct{}{}
result = append(result, value)
}
return result
}
func main() {
labels := []string{"go", "sql", "go", "go", "grpc", "sql"}
fmt.Println(Unique(labels)) // [go sql grpc]
fmt.Println(labels) // [go sql go go grpc sql]
}
The map answers “have I seen this?” and the result slice records the order. The function makes one pass and stores one map entry per distinct value. It uses Go equality, so it works for strings, integers and structs with comparable fields. With empty input this implementation returns a nil slice. Go specification on map keys
When does slices.Compact work?
slices.Compact collapses consecutive equal values. On [go sql go go grpc sql] the two adjacent go values become one, but the earlier go survives. If sorted output is acceptable, sort a copy and then compact it. Both operations can write into the supplied slice’s backing array, so keep the slice that Compact returns. Go slices package
package main
import (
"fmt"
"slices"
)
func main() {
labels := []string{"go", "sql", "go", "go", "grpc", "sql"}
fmt.Println(slices.Compact(slices.Clone(labels))) // [go sql go grpc sql]
sorted := slices.Clone(labels)
slices.Sort(sorted)
sorted = slices.Compact(sorted)
fmt.Println(sorted) // [go grpc sql]
}
What if two records have the same ID but different fields?
Key the map by the field that defines a duplicate. For example, with map[int]struct{} keyed by order.ID, two records with the same ID count as duplicates even if their timestamps differ. Appending the first record keeps the earliest one in input order. If the newest timestamp should win, compare timestamps explicitly.
If you only need membership checks, keep the set itself. If you want every record that matches a condition, including repeated records, use a slice filter.