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:
|
|
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:
|
|
This outputs:
116
101
115
116
105
110
103
This is cleaner than looping through a string using a for
loop without range
:
|
|
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