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
+2.6k Java : Get FX sentiment from website example
+12.7k Golang : Chunk split or divide a string into smaller chunk example
+4.4k Golang : Display advertisement images or strings on random order
+11.4k Golang : Get terminal width and height example
+29.2k Golang : Download file example
+7.2k Golang : How to check variable or object type during runtime?
+10.4k Golang : Convert(cast) bigint to string
+9.4k Golang : Get currencies exchange rates example
+6.1k Golang : Check if one string(rune) is permutation of another string(rune)
+10.2k Golang : How to flush a channel before the end of program?
+5.2k Golang : Test input string for unicode example
+11.2k Golang : Covert map/slice/array to JSON or XML format