Go language scope (Range)


Release date:2023-09-19 Update date:2023-10-13 Editor:admin View counts:370

Label:

Go language scope (Range)

Go in the language range keyword is used for for iterate the array in the loop, slice , channel or collection ( map ). Itreturns the values corresponding to the index of the element in arrays and slices and in the collection key-value.

Example

package main
import "fmt"
func main() {
    //This is how we use range to sum a slice.
    Using arrays is similar to this
    nums := []int{2, 3, 4}
    sum := 0
    for \_, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)

//Using range on an array will pass in two variables: index and value.
    We did not need to use the ordinal of the element in the above example,
    so we omitted it with the
    blank character "_". Sometimes we do need to know its index.
    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }
    //range can also be used on key value pairs in maps.
    kvs := map[string]string{"a": "apple", "b": "banana"}
    for k, v := range kvs {
        fmt.Printf("%s -> %s\\n", k, v)
    }

//Range can also be used to enumerate Unicode strings. The first parameter is the index of the character,
    and the second parameter is the character (Unicode value) itself.
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}

The output of the above instance is as follows:

sum: 9
index: 1
a -> apple
b -> banana
0 103
1 111

Powered by TorCMS (https://github.com/bukun/TorCMS).