0
0
GoProgramBeginner · 2 min read

Go Program to Reverse a String with Example and Explanation

To reverse a string in Go, convert it to a rune slice, swap characters from both ends using a loop, and then convert it back to a string, like this: 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] }; reversed := string(runes).
📋

Examples

Inputhello
Outputolleh
InputGoLang
OutputgnaLoG
Input
Output
🧠

How to Think About It

To reverse a string, think of it like flipping a row of letters. Since Go strings are made of bytes but can contain multi-byte characters, convert the string to a slice of runes to handle all characters correctly. Then swap the first and last characters, move inward, and keep swapping until you reach the middle. Finally, convert the runes back to a string.
📐

Algorithm

1
Convert the input string to a slice of runes to handle all characters properly.
2
Set two pointers: one at the start and one at the end of the rune slice.
3
Swap the runes at these two pointers.
4
Move the start pointer forward and the end pointer backward.
5
Repeat swapping until the pointers meet or cross.
6
Convert the rune slice back to a string and return it.
💻

Code

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() {
    input := "hello"
    fmt.Println(reverseString(input))
}
Output
olleh
🔍

Dry Run

Let's trace reversing the string "hello" through the code

1

Convert string to runes

Input string: "hello" -> runes: ['h', 'e', 'l', 'l', 'o']

2

Initialize pointers

i = 0 (points to 'h'), j = 4 (points to 'o')

3

Swap runes at i and j

Swap 'h' and 'o' -> runes: ['o', 'e', 'l', 'l', 'h']

4

Move pointers

i = 1 (points to 'e'), j = 3 (points to 'l')

5

Swap runes at i and j

Swap 'e' and 'l' -> runes: ['o', 'l', 'l', 'e', 'h']

6

Move pointers

i = 2, j = 2 (both point to 'l'), stop swapping

7

Convert runes back to string

Result string: "olleh"

ijrunes
04['o', 'e', 'l', 'l', 'h']
13['o', 'l', 'l', 'e', 'h']
22['o', 'l', 'l', 'e', 'h']
💡

Why This Works

Step 1: Convert to rune slice

Using []rune converts the string to runes so that multi-byte characters are handled correctly.

Step 2: Swap characters

Swapping runes from the start and end moves characters to their reversed positions.

Step 3: Convert back to string

After swapping, converting the rune slice back to a string gives the reversed string output.

🔄

Alternative Approaches

Using bytes slice (only for ASCII)
go
package main

import "fmt"

func reverseASCII(s string) string {
    b := []byte(s)
    for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
        b[i], b[j] = b[j], b[i]
    }
    return string(b)
}

func main() {
    fmt.Println(reverseASCII("hello"))
}
This works only for ASCII strings because bytes do not handle multi-byte characters correctly.
Using recursion
go
package main

import "fmt"

func reverseRec(s string) string {
    runes := []rune(s)
    if len(runes) <= 1 {
        return s
    }
    return string(runes[len(runes)-1]) + reverseRec(string(runes[:len(runes)-1]))
}

func main() {
    fmt.Println(reverseRec("hello"))
}
This method is elegant but less efficient due to repeated string slicing and function calls.

Complexity: O(n) time, O(n) space

Time Complexity

The algorithm loops through half of the string length swapping characters, so it runs in linear time O(n).

Space Complexity

Converting the string to a rune slice requires O(n) extra space to hold the characters.

Which Approach is Fastest?

The rune slice swap method is efficient and safe for all characters. The byte slice method is faster but only works for ASCII. Recursive methods are slower due to overhead.

ApproachTimeSpaceBest For
Rune slice swapO(n)O(n)All Unicode strings, safe and efficient
Byte slice swapO(n)O(n)ASCII strings only, faster but limited
Recursive reversalO(n^2)O(n^2)Small strings, simple code but inefficient
💡
Always convert strings to rune slices before reversing to handle all characters correctly in Go.
⚠️
Trying to reverse a string by converting it to a byte slice can break multi-byte characters like emojis or accented letters.