/ Go

How to reverse a string in Go

Sometimes you have the necessity to obtain a string, but reversed, but how to do this with Go?
Unfortunately Go has nothing built-in, so you have to use a custom function to achieve it.

The best solution is the following, where every character is transformed in a rune so it won't break with special encodings and all without the need to import any package.

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

If you want to test it out, you can write a simple program like this:

package main

import "fmt"
 
func main() {
  str := "The quick brown 狐 jumped over the lazy 犬"
  fmt.Println(reverse(str))
}

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

The function will return this: 犬 yzal eht revo depmuj 狐 nworb kciuq ehT.

If you don't believe me, try it in the interactive Go Playground!

Danilo Polani

Danilo Polani

Software Engineer and dreamer in startups. Go, Python, Laravel, Ionic, AngularJS, VueJS, NodeJS, JavaScript, Elasticsearch, Redis.

Read More