Range with Positions
Use both things range gives you.
1package main
2
3import "fmt"
4
5func main() {
6 fruits := []string{"apple", "banana", "cherry"}
7 for i, fruit := range fruits {
8 fmt.Println(i, fruit)
9 }
10}
$ go run main.go
0 apple
1 banana
2 cherry
Every line, explained
package main- Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"- import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {- func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
fruits := []string{"apple", "banana", "cherry"}- A slice is Go's list. []string means "a slice of strings", and the items go between curly braces. Every item must be the same type.
for i, fruit := range fruits {- This time we keep BOTH things range offers: i is the position (starting at 0) and fruit is the item at that position. No _ needed; we want them both.
fmt.Println(i, fruit)- fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Prints the position and the item together, like "0 apple".
}- This } closes the for loop.
}- This closing brace } ends func main.