25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started β†’
Reversing a String in Go
Code Snippet

Reversing a String in Go

go

Reversing strings in Go requires careful consideration of Unicode characters. While a simple byte-by-byte reversal might work for ASCII text, it will corrupt multi-byte Unicode characters like accented letters or emoji. The correct approach is to convert the string to a rune slice, where each rune represents a single Unicode character, reverse the slice, and convert back to a string.

A rune in Go represents a single Unicode code point, which can be multiple bytes. By converting to a rune slice first, you ensure that complex characters remain intact during the reversal operation. This is particularly important when working with internationalized text or emoji characters.

Here’s a comprehensive example showing proper string reversal with Unicode support:

package main

import (
  "fmt"
)

func main() {
  // Simple ASCII reversal
  text1 := "golang"
  runes1 := []rune(text1)
  for i, j := 0, len(runes1)-1; i < j; i, j = i+1, j-1 {
    runes1[i], runes1[j] = runes1[j], runes1[i]
  }
  fmt.Println(string(runes1)) // Output: gnalog

  // Unicode character reversal
  text2 := "Hello, δΈ–η•Œ! πŸš€"
  runes2 := []rune(text2)
  for i, j := 0, len(runes2)-1; i < j; i, j = i+1, j-1 {
    runes2[i], runes2[j] = runes2[j], runes2[i]
  }
  fmt.Println(string(runes2)) // Output: πŸš€ !η•ŒδΈ– ,olleH

  // Helper function for cleaner code
  reverseString := func(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
      r[i], r[j] = r[j], r[i]
    }
    return string(r)
  }
  fmt.Println(reverseString("ΠŸΡ€ΠΈΠ²Π΅Ρ‚")) // Output: Ρ‚Π΅Π²ΠΈΡ€ΠŸ
}

Understanding the distinction between bytes and runes is crucial for writing robust Go applications that handle international text correctly. Always use rune-based reversal to ensure your code works reliably with any Unicode content.

Further Reading:

If you found this snippet useful, you may also enjoy some of the other content on the site: