Go: Remove adjacent duplicates with slices.Compact
slices.Compact collapses adjacent equal elements. For a sorted list of distinct integers, sort a copy first and keep the shorter slice that Compact returns.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as slices_compact_adjacent_duplicates.go:
package main
import (
"fmt"
"slices"
)
func main() {
original := []int{3, 3, 1, 3, 1, 1}
adjacent := slices.Compact(slices.Clone(original))
sorted := slices.Clone(original)
slices.Sort(sorted)
sorted = slices.Compact(sorted)
fmt.Println("original:", original)
fmt.Println("adjacent:", adjacent)
fmt.Println("sorted distinct:", sorted)
}go run slices_compact_adjacent_duplicates.goObserved output:
original: [3 3 1 3 1 1]
adjacent: [3 1 3 1]
sorted distinct: [1 3]Read the result
The adjacent result still contains repeated values because other values separate them. Sorting brings every equal integer together. Cloning before each operation leaves the original order and contents available to the caller.
Apply it carefully
Compaction mutates the backing array and zeroes the removed tail; ignoring its return value retains the old slice length. Sorting changes order, so use a different approach if the first-occurrence order matters. These integer examples use ordinary equality; custom equivalence requires an explicitly chosen comparison policy.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- slices_compact_adjacent_duplicates.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.