Senior
How does DISTINCT work?
sobes.tech AI
Answer from AI
Go does not have a built-in DISTINCT function like SQL, but typically, DISTINCT refers to the operation of removing duplicates from a slice.
To implement DISTINCT in Go, you can use a map to track already encountered elements. For example:
func Distinct(slice []int) []int {
seen := make(map[int]struct{})
result := []int{}
for _, v := range slice {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
result = append(result, v)
}
}
return result
}
Thus, DISTINCT works by storing unique values in a map and creating a new slice without duplicates.