Range in Go

Range

range iterates over elements in a variety of data structures like array, slices, maps etc.

range on array and slices


    nums := []int{1, 2, 3, 4}
    sum := 0
    for i, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)
    //sum: 10

    // loop over an array/a slice
    for i, e := range a {
        // i is the index, e the element
    }

    // if you only need e:
    for _, e := range a {
        // e is the element
    }

    // ...and if you only need the index
    for i := range a {
    }

range on maps

    alphabetes := map[string]string{"a": "apple", "b": "banana"}
    for k, v := range alphabetes {
        fmt.Printf("%s -> %s\n", k, v)
    }

    //a -> apple
    //b -> banana

Previous Article