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 PHP : How to check if an array is empty ?
+37.8k Golang : How to iterate over a []string(array)
+4.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+8.9k Golang : Use regular expression to get all upper case or lower case characters example
+10.7k Golang : md5 hash of a string
+10.7k Golang : Detect user location with HTML5 geo-location
+13.4k Golang : Get URI segments by number and assign as variable example
+4.3k Gogland : Datasource explorer
+7.8k Golang : Capture text return from exec function example
+17.2k Golang : Write file with io.WriteString
+13.1k Golang : How to get URL port?
+25.1k Golang : Encrypt and decrypt data with AES crypto