Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang sorting slices by name

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)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading