Golang : Fix - does not implement sort.Interface (missing Len method)
Problem:
You are trying to use the sort.Sort()
or sort.Reverse()
functions on type []string
data but encounter this error message:
cannot use strSlice (type []string) as type sort.Interface in argument to sort.Sort: []string does not implement sort.Interface (missing Len method)
What's going on and how to fix this?
Solution:
Cast the []string
slice/array to type StringSlice or if you are dealing integer or float - cast to IntSlice or Float64Slice type first before using the sort.Sort()
function.
To cast/convert the []string
slice/array, use sort.StringSlice()
function.
For example:
package main
import (
"fmt"
"sort"
"strings"
)
func main() {
str := "Dog,Apple,Cat,Boy"
strSlice := strings.Split(str, ",")
fmt.Println("Before : ", strSlice)
sortableStrSlice := sort.StringSlice(strSlice) <------- here!
sort.Sort(sortableStrSlice)
fmt.Println("After : ", sortableStrSlice)
}
Output:
Before : [Dog Apple Cat Boy]
After : [Apple Boy Cat Dog]
Happy coding!
See also : Golang : Reverse IP address for reverse DNS lookup example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.1k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+16.6k Golang : [json: cannot unmarshal object into Go value of type]
+5k Javascript : How to replace HTML inside <div>?
+9k Golang : List available AWS regions
+12.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+7.9k Golang : Accept any number of function arguments with three dots(...)
+4.3k Golang : micron to centimeter example
+5k Linux : Disable and enable IPv4 forwarding
+10.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+5.4k Golang & Javascript : How to save cropped image to file on server
+24.8k Golang : missing Mercurial command
+17.5k Golang : Write file with io.WriteString