Why does sorted "tan" != "ant"?

Jos*_*ark 1 sorting string go

I'm trying to sort the characters in a string by sorting a slice of the bytes in the string (using sort.Slice). The code I'm using gets the right results sometimes but other times produces results I can't make sense of.

package main

import (
    "fmt"
    "sort"
)

func main() {
    for _, s := range []string{"nat", "tan", "ant"} {
        b := []byte(s)
        sort.Slice(b, func(i int, j int) bool { return s[i] < s[j] })
        fmt.Println(s, string(b))
    }
}
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/bC9QWq7aF3G

I would expect "nat", "tan" and "ant" to all be sorted to "ant", but "tan" is sorted to "atn".

Dar*_*tle 5

Change your sort.Slice line to:

sort.Slice(b, func(i int, j int) bool { return b[i] < b[j] })
Run Code Online (Sandbox Code Playgroud)

sort.Slice needs your less function to compare values in the slice in order to sort the way you intended. Your bug is that you used s rather than b in your less function.