How to Reverse a String in Golang

Reversing a string is one of the fundamental exercises when learning any programming language. In Golang, reversing a string is slightly more complex than in some other languages due to its unique handling of strings. In this blog, we’ll explore why reversing a string in Go requires attention to detail and how to achieve it efficiently.


Understanding Strings in Go

In Go, a string is a read-only slice of bytes. Unlike some languages where strings are directly treated as arrays of characters, Go represents strings in UTF-8 encoding. This means each character (or rune) may take one or more bytes.

For example:

s := "Hello, 世界"  
fmt.Println(len(s)) // Outputs 13, not 9 (number of characters)  

Here, the Chinese characters “世” and “界” occupy more than one byte each.


Challenges in Reversing Strings

Because Go strings are byte slices, reversing them naively might lead to breaking multibyte characters. For instance, reversing "世界" byte by byte results in a corrupted string. To handle this correctly, we must work with runes, which are Go’s representation of Unicode code points.


Reversing a String in Go

Here’s a step-by-step guide to reversing a string in Go:

1. Convert the String to Runes

Converting the string to a slice of runes ensures that multibyte characters are handled correctly.

2. Reverse the Rune Slice

Use a simple loop to swap elements in the rune slice.

3. Convert the Rune Slice Back to a String

Finally, convert the reversed slice of runes back to a string.


Code Implementation

Below is the Go code to reverse a string:

package main

import (
	"fmt"
)

func reverseString(s string) string {
	// Convert the string to a slice of runes
	runes := []rune(s)
	
	// Reverse the slice of runes
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	
	// Convert the slice of runes back to a string
	return string(runes)
}

func main() {
	// Test the function
	input := "Hello, 世界"
	fmt.Println("Original String:", input)
	reversed := reverseString(input)
	fmt.Println("Reversed String:", reversed)
}

Output

Original String: Hello, 世界  
Reversed String: 界世 ,olleH

Explanation of the Code

  1. []rune(s): Converts the input string to a slice of runes. This step ensures proper handling of Unicode characters.
  2. Reversing the Slice: A simple two-pointer approach swaps the runes from both ends of the slice.
  3. string(runes): Converts the reversed rune slice back to a string.

Edge Cases

  • Empty String: The function gracefully handles an empty string by returning an empty string.
  • Single-Character String: No changes are needed as the character is already “reversed.”
  • Strings with Multibyte Characters: The rune-based approach ensures that these are reversed correctly.

Performance

Reversing a string in Go using this approach is efficient, with a time complexity of O(n) and space complexity of O(n) due to the creation of a rune slice.


Conclusion

Reversing a string in Go is an excellent exercise to understand the language’s handling of strings and Unicode. By working with runes, you can safely reverse strings without corrupting multibyte characters.

Try implementing the function yourself, and experiment with different inputs to see how Go handles strings under the hood!