Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

For loop in slice - iterate over slice

  • range
  • for
package main

import (
	"fmt"
)

func main() {
	dwarfs := []string{"Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey"}

	fmt.Printf("%T\n%v\n", dwarfs, dwarfs)

	for i, name := range dwarfs {
		fmt.Printf("location: %d  name: %s\n", i, name)
	}
}
[]string
[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
location: 0  name: Doc
location: 1  name: Grumpy
location: 2  name: Happy
location: 3  name: Sleepy
location: 4  name: Bashful
location: 5  name: Sneezy
location: 6  name: Dopey