Back to Basics: Reversing a string in Golang

Go is created by the co-authors involved in creating C. Yes, it has a rich standard library. But yet it is not considered “battery-included” like Python.

In Python, to reverse a string, we do this:

aString = ""A string to reverse with python"
aString = aString[::-1]

It’s cryptic but once you get the hang of the zen of Python, you got the power.

That being said, I learnt Go as my second main programming language, okay, third and suddenly reversing string is more involved, as can be seen with this code snippet.

import "fmt"func reverse(r []rune) string {
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
result := string(r)
return result
func main() { //string to reverse
s := "A string to reverse with golang."
r := []rune(s) fmt.Printf("text reversed %s\n", reverse(r))


$ go run main.go
text reversed .gnalog htiw esrever ot gnirts A

Granted, it’s more involved. But Go’s ability to work with multiple variable assignment is makes short work and in my opinion a breath of fresh air compared to C. Also as I was writing the code in order to do my work, it makes me think and keep me engaged, more than using the simple one liner Python code. Sometimes, being too zen may not be that great :P

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store