How to Iterate Over String Characters in Go: Simple Guide
In Go, you can iterate over string characters using a
for range loop, which reads each Unicode character (rune) correctly. This loop gives you the index and the character value, allowing safe iteration over multi-byte characters.Syntax
The basic syntax to iterate over string characters in Go uses the for range loop. It looks like this:
for index, char := range str {
// use index and char
}Here, str is your string, index is the byte position of the character, and char is the Unicode code point (rune) of the character.
go
for index, char := range str { // use index and char }
Example
This example shows how to print each character of a string on a new line, including Unicode characters like emojis or accented letters.
go
package main import "fmt" func main() { str := "Hello, δΈηπ" for index, char := range str { fmt.Printf("Character at byte %d is %c\n", index, char) } }
Output
Character at byte 0 is H
Character at byte 1 is e
Character at byte 2 is l
Character at byte 3 is l
Character at byte 4 is o
Character at byte 5 is ,
Character at byte 6 is
Character at byte 7 is δΈ
Character at byte 10 is η
Character at byte 13 is π
Common Pitfalls
A common mistake is to iterate over a string using a simple for i := 0; i < len(str); i++ loop and access characters by str[i]. This reads bytes, not characters, which breaks for multi-byte Unicode characters.
Use for range to get full characters safely.
go
package main import "fmt" func main() { str := "δΈη" fmt.Println("Wrong way:") for i := 0; i < len(str); i++ { fmt.Printf("Byte %d: %c\n", i, str[i]) } fmt.Println("Right way:") for _, char := range str { fmt.Printf("Character: %c\n", char) } }
Output
Wrong way:
Byte 0: δΈ
Byte 1: η
Right way:
Character: δΈ
Character: η
Quick Reference
- Use
for rangeto iterate over characters safely. - Index in
for rangeis byte position, not character count. - Characters are returned as runes (Unicode code points).
- Do not use simple byte indexing for Unicode strings.
Key Takeaways
Use
for range loops to iterate over string characters safely in Go.The loop returns the byte index and the Unicode character (rune) at that position.
Avoid indexing strings by bytes when working with Unicode characters.
Unicode characters may take multiple bytes, so simple byte loops can break characters.
Always treat strings as sequences of runes when iterating characters.