2
\$\begingroup\$

I'm trying to return unique items in a Go slice. I've landed on the following, but it seems rather sub-optimal. I'm new to golang (first project in it) and wondering if there's a better way to approach this?

// 
// Returns unique items in a slice
//
func Unique(strSlice []string) []string {
    keys := make(map[string]bool)
    list := []string{} 
    for _, entry := range strSlice {
        if _, value := keys[entry]; !value {
            keys[entry] = true
            list = append(list, entry)
        }
    }    
    return list
}
\$\endgroup\$
4
\$\begingroup\$

This is not idiomatic writing style in Go, because the value variable is misleading:

if _, value := keys[entry]; !value {

The first returned value is the value in the map, the second value indicates success or failure of the lookup. So rename it to ok or found.

If the slice is very large, then list = append(list, entry) may lead to repeated allocations. In that case, you can optimize by preallocating list to the maximum possible capacity (len(strSlice)), and assign elements by index rather than using append. But if you have no reason for this optimization then don't do it, that would be premature optimization, the current solution is fine.

\$\endgroup\$
1
\$\begingroup\$

Instead of creating you final slice during the loop, you could do two loops: one for creating the map and another to turn it into a slice:

//
// Returns unique items in a slice
//
func Unique(slice []string) []string {
    // create a map with all the values as key
    uniqMap := make(map[string]struct{})
    for _, v := range slice {
        uniqMap[v] = struct{}{}
    }

    // turn the map keys into a slice
    uniqSlice := make([]string, 0, len(uniqMap))
    for v := range uniqMap {
        uniqSlice = append(uniqSlice, v)
    }
    return uniqSlice
}

If your are not interested into the value of the map, it is customary to store the empty struct{}.

NB: this implementation will not keep any ordering of the input slice

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.