Remove Consecutive Duplicates in Go with slices.Compact
If a Go slice contains repeated values next to each other, you don’t need to write an index-heavy loop to collapse them. Since Go 1.21, slices.Compact handles that operation directly for comparable element types. The word consecutive matters. Given []string{"api", "api", "web", "api"}, the result is []string{"api", "web", "api"}. The last "api" stays because it belongs to a different run. slices.Compact isn’t a general-purpose “unique values” function. What slices.Compact actually does slices.Compact replaces each consecutive run of equal elements with its first element. It modifies the slice’s backing array and returns a slice with the resulting length.