iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐀
How to Remove Duplicates and Create Unique Slices in Go
It's as the title says.
We will use slices.Compact().
Looking at the description for slices.Compact(), it states the following:
Compact replaces consecutive runs of equal elements with a single copy. This is like the uniq command found on Unix. Compact modifies the contents of the slice s; it does not create a new slice. When Compact discards m elements in total, it might not modify the elements s[len(s)-m:len(s)]. If those elements contain pointers you might consider zeroing those elements so that objects they reference can be garbage collected.
Since it says it replaces consecutive runs of equal elements with a single copy, we first execute slices.Sort() and then slices.Compact().
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
strs := []string{"A", "B", "C", "A", "A", "D", "B", "E", "F"}
slices.Sort(strs)
unique := slices.Compact(strs)
fmt.Printf("%+v\n", unique)
}
output
[A B C D E F]
Program exited.
If you want to use a map, do the following:
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
)
func main() {
strs := []string{"A", "B", "C", "A", "A", "D", "B", "E", "F"}
var unique []string
encounter := map[string]int{}
for _, v := range strs {
if _, ok := encounter[v]; !ok {
encounter[v] = 1
unique = append(unique, v)
} else {
encounter[v]++
}
}
fmt.Printf("%+v\n", unique)
fmt.Printf("%+v", encounter)
}
output
[A B C D E F]
map[A:3 B:2 C:1 D:1 E:1 F:1]
Program exited.
Discussion