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
+17k Golang : Get input from keyboard
+9.1k Golang : Intercept and compare HTTP response code example
+24.1k Golang : Upload to S3 with official aws-sdk-go package
+6.1k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+9.7k Golang : Load ASN1 encoded DSA public key PEM file example
+15.6k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+7.3k Golang : Individual and total number of words counter example
+4.6k JavaScript : Rounding number to decimal formats to display currency
+21.1k Golang : For loop continue,break and range
+18.4k Golang : Logging with logrus
+8.4k Golang : Convert word to its plural form example
+4.4k Linux/MacOSX : Search and delete files by extension