Today I learned you can use for...range loops in Go to iterate over a string. There is no need to split the string first like in other programming languages.

Here’s an example:

1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
	for i, v := range "testing" {
		fmt.Printf("index: %d, char: %d\n", i, v)
	}
}

This outputs:

index: 0, char: t
index: 1, char: e
index: 2, char: s
index: 3, char: t
index: 4, char: i
index: 5, char: n
index: 6, char: g

Without any formatting from fmt.Printf each character in the string is printed out in its Unicode form:

1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
	for _, v := range "testing" {
		fmt.Println(v)
	}
}

This outputs:

116
101
115
116
105
110
103

This is cleaner than looping through a string using a for loop without range:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import "fmt"

func main() {
	str := "testing"

	for i := 0; i < len(str); i++ {
		fmt.Printf("index: %d, char: %c\n", i, str[i])
	}
}

As a side note, strings in Go are basically slices of bytes. This is why we can iterate through them using range like we would a typical slice.

From https://go.dev/blog/strings:

In Go, a string is in effect a read-only slice of bytes

References