Go Learning notes: Range function

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The range function is a magical and interesting built-in function that you can use to iterate through arrays, slices, and dictionaries.

When used to iterate over arrays and slices, the range function returns indexes and elements;

package mainimport  "FMT" Func main ()  {    //  Here we use range to calculate all the elements of a slice and     //  this method applies to the array     nums := [] Int{2, 3, 4}    sum := 0    for _, num  := range nums {        sum += num     }    fmt. Println ("Sum:",  sum)     // range  returns index and element values when used to iterate over arrays and slices      //  If we don't care the index can use an underscore (_) to ignore this return value     //  of course we sometimes need this index      for i, num := range nums {         If num == 3 {            fmt. Println ("index:",  i)         }    }&NBsp;   //  returns a key-value pair when using range to traverse the dictionary.     kvs := map[string]string{"A":  "Apple",  "B":  "banana"}     for k, v := range kvs {         fmt. Printf ("%s -> %s\n",  k, v)     }    //  The range function returns a Unicode code point when it is used to traverse a string.     //  The first return value is the index of the starting byte of each character, and the second is the character code point,    //  because the string of go is made up of bytes, Multiple bytes form a rune type character.     for i, c := range  "Go"  {         fmt. Println (I, c)     }}

The output result is

SUM:9INDEX:1A, Appleb, banana0 1031 111


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.