WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Range

The range keyword in the Go language is used to iterate over the elements of an array, slice, channel, or map in a for loop. In arrays and slices it returns the value of the index and index of the element, and returns a key-value pair in the collection.
Range expression 1st Value second Value(Optional)
Array or slice a [n]E index I int a[i] E
String s string kind index I int rune int
map m map[K]V key alright K fee m[k] V
channel c chan E element e E none

example

example

package main
import "fmt"
func main() {
    //This is the sum we use to find a slice. Using arrays is very similar to this
    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)
    //Use range on an array to pass in two variables, index and value. For the example above, we don't need to use the sequence number of the element, so we omit it with the whitespace "_". 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 map key-value pairs。
    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 argument is the index of the character, and the second is the character (the value of Unicode) itself.
    for i, c := range "go" {
        fmt.Println(i, c)
    }
}

The above example runs the output as:

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