0
0
GoHow-ToBeginner · 3 min read

How to Iterate Over String in Go: Simple Guide

In Go, you can iterate over a string using a for loop with range, which gives you the index and the Unicode character (rune) at that position. This method handles multi-byte characters correctly, unlike iterating by byte index.
📐

Syntax

Use a for loop with range to iterate over a string. It returns the index and the rune (Unicode code point) at that position.

  • index: position of the character in bytes
  • char: the Unicode character (rune)
go
for index, char := range str {
    // use index and char
}
💻

Example

This example shows how to print each character and its byte index from a string containing English and emoji characters.

go
package main

import "fmt"

func main() {
    str := "Go 🐹!"
    for index, char := range str {
        fmt.Printf("Index: %d, Character: %c\n", index, char)
    }
}
Output
Index: 0, Character: G Index: 1, Character: o Index: 2, Character: Index: 3, Character: 🐹 Index: 7, Character: !
⚠️

Common Pitfalls

Iterating over a string by byte index (using for i := 0; i < len(str); i++) can break multi-byte characters like emojis or accented letters. This causes incorrect characters or errors.

Always use range to get full characters (runes) safely.

go
package main

import "fmt"

func main() {
    str := "Go 🐹!"
    fmt.Println("Wrong way (by byte):")
    for i := 0; i < len(str); i++ {
        fmt.Printf("%c ", str[i])
    }
    fmt.Println("\nRight way (by rune):")
    for _, char := range str {
        fmt.Printf("%c ", char)
    }
}
Output
Wrong way (by byte): G o ï  Right way (by rune): G o 🐹 !
📊

Quick Reference

  • Use for index, char := range str to iterate characters safely.
  • Index is byte position, char is rune (Unicode character).
  • Do not iterate by byte index for strings with multi-byte characters.

Key Takeaways

Use for-range loop to iterate over string characters safely in Go.
Range returns byte index and Unicode character (rune) for each iteration.
Avoid iterating by byte index to prevent breaking multi-byte characters.
The index from range is byte position, not character count.
This method works correctly with emojis and accented letters.