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:
package main
import "fmt"
func main() {
for i, v := range "testing" {
fmt.Printf("index: %d, char: %c\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: gWithout any formatting from fmt.Printf each character in the string is printed out in its Unicode form:
package main
import "fmt"
func main() {
for _, v := range "testing" {
fmt.Println(v)
}
}This outputs:
116
101
115
116
105
110
103This is cleaner than looping through a string using a for loop without range:
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: