Go language Range (range)

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

Go language Range (range)

The range keyword in the Go language is used for elements of an array, slice (slice), linked list (channel), or collection (map) in a for loop. It returns the index value of the element in the array and the slice, and returns the key value of the Key-value pair in the collection.

Instance

 PackageMainImport "FMT"Func main() {    //This is where we use range to find a slice and. Using arrays is similar to thisNums:= []int{2, 3, 4}sum:= 0     for _,Num:=Range Nums{sum+=Num}FMT.Println("sum:",sum)    //Use range on the array to pass in index and value two variables. In the above example, we don't need to use the ordinal of the element, so we omit it with the whitespace character "_". Sometimes we really need to know its index.      forI,Num:=Range Nums{        ifNum== 3 {FMT.Println("Index:",I)        }    }    //range can also be used on map key-value pairs. KVS:=Map[string]string{"a": "Apple", "B": "Banana"}     fork,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 Unicode value) itself.      forI,C:=Range"Go" {FMT.Println(I,C)    }}

The above example runs the output as:

sum: 9Index: 1a -Appleb -Banana0 1031 111
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.