0
0
GoHow-ToBeginner · 3 min read

How to Reverse a String in Go: Simple Guide with Example

To reverse a string in Go, convert the string to a slice of runes to handle Unicode characters properly, then swap elements from start to end. Use a loop to reverse the rune slice and convert it back to a string with string().
📐

Syntax

To reverse a string in Go, follow these steps:

  • Convert the string to a []rune to support Unicode characters.
  • Use a loop to swap runes from the start and end moving towards the center.
  • Convert the reversed rune slice back to a string using string().
go
func reverseString(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)
}
💻

Example

This example shows how to reverse a string containing both ASCII and Unicode characters correctly.

go
package main

import (
    "fmt"
)

func reverseString(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)
}

func main() {
    original := "Hello, 世界"
    reversed := reverseString(original)
    fmt.Println("Original:", original)
    fmt.Println("Reversed:", reversed)
}
Output
Original: Hello, 世界 Reversed: 界世 ,olleH
⚠️

Common Pitfalls

Many beginners try to reverse a string by converting it to a []byte slice, which breaks Unicode characters and causes incorrect output for non-ASCII text.

Always use []rune to handle multi-byte characters properly.

go
package main

import (
    "fmt"
)

// Wrong way: reverses bytes, breaks Unicode
func reverseBytes(s string) string {
    bytes := []byte(s)
    for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
        bytes[i], bytes[j] = bytes[j], bytes[i]
    }
    return string(bytes)
}

// Correct way: reverses runes
func reverseRunes(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)
}

func main() {
    s := "Hello, 世界"
    fmt.Println("Wrong reversal:", reverseBytes(s))
    fmt.Println("Correct reversal:", reverseRunes(s))
}
Output
Wrong reversal: 界�,olleH Correct reversal: 界世 ,olleH
📊

Quick Reference

  • Use []rune to handle Unicode characters.
  • Swap runes from start to end using a loop.
  • Convert runes back to string with string().
  • Avoid reversing bytes directly to prevent broken characters.

Key Takeaways

Always convert strings to []rune before reversing to handle Unicode correctly.
Use a loop to swap runes from the start and end moving inward.
Avoid reversing []byte slices directly as it breaks multi-byte characters.
Convert the reversed rune slice back to string using string() function.
Test with Unicode strings to ensure your reversal works correctly.