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