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
+8.9k Golang : Get current, epoch time and display by year, month and day
+6.9k Golang : get the current working directory of a running program
+13.2k Golang : How to get URL port?
+9.5k Golang : Flip coin example
+15.1k Golang :Trim white spaces from a string
+42.7k Golang : Use wildcard patterns with filepath.Glob() example
+4.6k Javascript : Shuffle or randomize array example
+8.5k Golang : Qt get screen resolution and display on center example
+15.2k Golang : Check if a string contains multiple sub-strings in []string?
+5.3k Golang & Javascript : How to save cropped image to file on server
+12.6k Golang : Check if an integer is negative or positive
+6.3k Golang : Dealing with postal or zip code example