How to use the statement to iterate through arrays/slices and iterate through strings.
Iterating through arrays/slices
An array/slice is a collection of items in Go.
For example, OS is an array of three elements.
var students [3]string students[0] = "Adam" students[1] = "Alice" students[2] = "Ben"
To iterate through each of the elements in the array, you use the for-range loop.
package main import ( "fmt" ) func main() { var students [3]string students[0] = "Adam" students[1] = "Alice" students[2] = "Ben" for i, v := range students { fmt.Println(i, v) } }
The range keyword returns the following values.
- i: The index of the value you’re accessing
- v: Each of the values in the Students array.
The previous code snippet prints out the following
0 Adam 1 Alice 2 Ben
If you don’t want the index, you can use a blank identifier.
package main import ( "fmt" ) func main() { var students [3]string students[0] = "Adam" students[1] = "Alice" students[2] = "Ben" for _, v := range students { fmt.Println(v) } }
Adam Alice Ben
Same for the value
package main import ( "fmt" ) func main() { var students [3]string students[0] = "Adam" students[1] = "Alice" students[2] = "Ben" for i, _ := range students { fmt.Println(i) } }
Or you can omit the blank identifier entirely.
package main import ( "fmt" ) func main() { var students [3]string students[0] = "Adam" students[1] = "Alice" students[2] = "Ben" for i := range students { fmt.Println(i) } }
0 1 2
Iterating through a string
- One of the most common operations involving strings is going through each of the characters in a string and finding the characters you want.
- In Go, a string is essentially a read-only slice of bytes.
- So, you can use the for-range loop to extract each of the characters in the string.
package main import ( "fmt" ) func main() { for pos, char := range "Hello, From Mars" { fmt.Println(pos, char) } }
The above code produces the Unicode code for each character in the string. A Unicode code of 72
is the numerical representation of the H
character.
0 72 1 101 2 108 3 108 4 111 5 44 6 32 7 70 8 114 9 111 10 109 11 32 12 77 13 97 14 114 15 115
- Unicode, which uses numbers to represent characters, is a standard for encoding, representing, and handling text.
- It’s a widely used standard for encoding text documents on computers.
When you iterate through a string using the for-range loop, the value you get for each character is the Unicode value.
If you want to get the actual character, use the Printf()
function (with the %c
format specifier) from the fmt package
.
package main import ( "fmt" ) func main() { for pos, char := range "Hello From Mars" { fmt.Printf("%d %c\n", pos, char) } }
With the Above Code, Snippet now gets the following output.
0 H 1 e 2 l 3 l 4 o 5 6 F 7 r 8 o 9 m 10 11 M 12 a 13 r 14 s