How to reverse a string in Go?

user211499 picture user211499 · Nov 17, 2009 · Viewed 71.5k times · Source

How can we reverse a simple string in Go?

Answer

yazu picture yazu · Apr 5, 2012

In Go1 rune is a builtin type.

func Reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}