Golang of Learning: Range Usage Summary

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

1. When range acts on a string, the first return value is index and the second is Char

str: = "Hello World"

for index, ch: = Range str {

FMT. Printf ("%d---%c\n", index, CH)

}


2. When range acts on an array, the first return value is index and the second is value

Func PrintArray (Array [5]int) {

for index, res: = range Array {

FMT. PRINTLN (Index, "--", RES)

}

}


Func Main () {

array: = [5]int{1,2,3,4,5}

PrintArray (Array)

}


3. When range is acting on slice, the first return value is index and the second is value

Arr: = [10]int {1,2,3,4,5,6,7,8,9,10}

var Slice1 []int = Arr[:5]

For _, Res: = Range Slice1 {

FMT. Println (RES)

}


4, this is not a range of the use of the map, the first value of the return values, the second time is OK

Type person struct {

ID String

Name String

Addr String

}

Func Main () {

var persons map[string] person = do (map[string] person)

persons["123"] = person {"123", "Heihei", "haha"}

p, OK: = persons["123"]

if OK {

FMT. Println (P.name)

}

...


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.