Senior
1. What will be output, how to fix, how to make thread-safe (waitGroup) 2. Remove duplicates in a slice
sobes.tech AI
Answer from AI
- What will it output, how to fix it, how to make it thread-safe (waitGroup)
It's hard to say exactly without specific code, but a common mistake with sync.WaitGroup in Go is incorrect usage of the Add, Done, and Wait methods, which can lead to panics or deadlocks.
An example of correct usage:
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// work
}()
wg.Wait()
It's important to call Add before starting the goroutine to avoid race conditions.
To make it thread-safe, you need to properly synchronize access to shared data, for example, using mutexes or channels.
- Remove duplicates from a slice
Example function to remove duplicates from a slice of strings:
func removeDuplicates(slice []string) []string {
seen := make(map[string]struct{})
result := []string{}
for _, v := range slice {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
result = append(result, v)
}
}
return result
}
For other types, a similar approach with a map to track unique elements can be used.