Go by Example: Range, gobyexamplerange

Source: Internet
Author: User

Go by Example: Range, gobyexamplerange

UseRangeIt can traverse elements in various data structures. Let's see how to useRangeTraverse data structures that we have learned.

Package mainimport "fmt" func main () {// here we use range traversal slice to sum // This method also applies to arrays. Nums: = [] int {2, 3, 4} sum: = 0 for _, num: = range nums {sum + = num} fmt. println ("sum:", sum) // when range is used to traverse arrays and slices, index and element value are returned ). // if you do not care about the index, you can use a null value operator (_) to ignore this return value. // Of course, we also need this index sometimes. For I, num: = range nums {if num = 3 {fmt. println ("index:", I) }// when range is used to traverse the dictionary, the key-value Pair (key/value) is returned ). Kvs: = map [string] string {"a": "apple", "B": "banana"} for k, v: = range kvs {fmt. printf ("% s-> % s \ n", k, v)} // The Unicode code point is returned when the range function is used to traverse strings. // The first return value is the index of the starting byte of each character, and the second value 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.


Original ENGLISH


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.