Junior — Senior
Competitive extraction of unique slice elements
livecode
Task condition
Given an array of integers: values := []int{3, 3, 2, 1, 2, 1, 1, 2, 4}. You need to print each distinct element exactly once, using multiple goroutines. The order of output does not matter, but there should be no duplicates. In the original example, a data race occurs when writing to a regular map, leading to incorrect results. You need to fix the code to ensure safe concurrent access to the shared structure (for example, using a mutex or sync.Map).
func main() {
values := []int{3, 3, 2, 1, 2, 1, 1, 2, 4}
var idx sync.Map
for _, v := range values {
go func(val int) {
if _, ok := idx.Load(val); ok {
return
}
idx.Store(val, struct{}{})
log.Println(val)
}(v)
}
}