I have an slice of structs which have a property name of type string and I need to sort the slice alphabetically by name of the struct with it not being case sensitive.
Bellow is the code every example gives where they sort a slice of string, witch would work for me, but the problem is that this code only takes into account the first letter of the string. So if you would try to print the code out Ab would be put before Aa and I would like the code to take into account every letter of the string and not only the first one.
Has anyone encountered this and maybe you have a solution? Thank you.
package main
import (
"fmt"
"sort"
"strings"
)
type byLength []string
func (s byLength) Len() int {
return len(s)
}
func (s byLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byLength) Less(i, j int) bool {
return []rune(strings.ToLower(s[i]))[0] < []rune(strings.ToLower(s[j]))[0]
}
func main() {
data := []string{"Ab", "Aa", "D", "c"}
sort.Sort(byLength(data))
fmt.Println(data)
}
>Solution :
The error is in the implementation of the Less method. You’re just evaluating the first character of the string (casting as a slice of rune and then taking the first letter). Change the implementation of the method to this:
func (s byLength) Less(i, j int) bool {
return s[i] < s[j]
}