Interesting phenomena about the Go Language array index

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

On Twitter I saw Dave Cheney a pop quiz My curiosity and guess the results of the following code.

Package Mainimport "FMT" Func Main () {a: = [...] Int{5, 4:1, 0, 2:3, 2, 1:4}fmt. Println (A)}

Go run and the results come out, but the interesting thing is,

[5 4 3 2 1 0]

Here's an analysis of what's going on in one step.

[Number:value] In the array of go represents the value at the index at the position of not number, and resets if the index value is out of bounds.

5 _ _ _ _ _ index:0, Value:5

5 _ _ 1 _ Index:4, value:1

5 _ _ _ 1 0 index:5, value:0 because the element index of the previous operation is 4 ([4:1]), the element index of the next operation is automatically added 1

5 _ 3 _ 1 0 index:2, Value:3

5 _ 3 2 1 0 index:3, value:2 because the element index of the previous operation is 2 ([2:3]), the element index of the next operation is automatically added 1

5 1 3 2 1 0 index:1, Value:4

The order in which the array elements are manipulated is ordered in the order in which they are declared. 5 1 0 3 2 4 This is the order in which the operation is performed.

So if you change the code, you'll get an error, such as the following example

Package Mainimport "FMT" Func Main () {a: = [...] Int{5, 4:1, 0, 2:3, 2, 1:4, 10}fmt. Println (A)}

Results

Prog.go:6: Duplicate index in array literal:2 [process exited with Non-zero status]

The error message is that the second index is duplicated.

Then the above analysis

5 1 3 2 1 0 index:1, value:4 at this point, if you continue to manipulate the next element, add 1 to the rule index

Which is to value:10 the elements of the index:2, but we've already assigned the index to 2 o'clock, so there's an exception.

Duplicate index in array literal:2
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.