Go by Example:range

Source: Internet
Author: User

Use range to traverse elements in a variety of data structures. Let's see how to use range to traverse some of the data structures we've already learned.

Package Mainimport "FMT" Func Main () {//    here we use range traversal slice to sum    //This method is also applicable to the array.    nums: = []int{2, 3, 4}    sum: = 0 for    _, num: = range nums {        sum + = num    }    fmt. Println ("sum:", sum)    //range is used to iterate through arrays and slices, returning index and element value (value).    If we don't care, the index can use a null-value definition (_) to ignore this return value    //And we sometimes need this index.    for i, num: = Range nums {        if num = = 3 {            FMT. Println ("Index:", i)        }    }    //When using range to traverse the dictionary, return the key-value pair (key/value).    KVS: = map[string]string{"A": "Apple", "B": "Banana"}    for K, V: = range KVS {        fmt. Printf ("%s-%s\n", K, V)    }    //The range function is used to iterate through a string, returning a Unicode code point. The    first return value is the index of the starting byte of each character, and the second is the Rune character.    for I, c: = Range "Go" {        fmt. Println (i, C)    }}
Output
$ go Run range.go sum:9index:1a, Appleb, banana0 1031 111


Next example: Go by Example:functions.


English original


Go by Example:range

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.