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
+14.1k Golang : How to check if your program is running in a terminal
+5.2k How to check with curl if my website or the asset is gzipped ?
+14k Golang : How to pass map to html template and access the map's elements
+19.7k Golang : Determine if directory is empty with os.File.Readdir() function
+6k Golang : How to search a list of records or data structures
+11.2k Golang : Handle API query by curl with Gorilla Queries example
+4.4k Mac OSX : Get disk partitions' size, type and name
+11.9k Golang : md5 hash of a string
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.5k Golang : convert(cast) float to string
+25k Golang : Daemonizing a simple web server process example
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file