Reverse Slice of strings


I don’t understand what is wrong with the below implementation, I had a look at sort.StringSlice and it looks the same.

type RevStr []string

func(s RevStr) Len() int { return len(s) }
func(s RevStr) Less(i, j int) bool { return s[i] < s[j] }
func(s RevStr) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func Reverse(input string) string {
  rs := RevStr(strings.Split(input, " "))
  return strings.Join(rs, " ")


sort.Reverse doesn’t sort the data, but rather returns a new sort.Interface that will sort the data in reverse order. So you don’t really need your own type:

func Reverse(input string) string {
    s := strings.Split(input, " ")
    return strings.Join(s, " ")


EDIT: If you just need to reverse a slice of strings, just do:

func reverse(ss []string) {
    last := len(ss) - 1
    for i := 0; i < len(ss)/2; i++ {
        ss[i], ss[last-i] = ss[last-i], ss[i]


Answered By – Ainar-G

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.