Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About golang array

Tags:

go

a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4 }
fmt.Println(a)

the result is [5 4 3 2 1 0]. How it's sort?

a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4 ,12,11,10}
fmt.Println(a)

the result is

prog.go:8: duplicate index in array literal: 2
prog.go:8: duplicate index in array literal: 3
prog.go:8: duplicate index in array literal: 4
 [process exited with non-zero status]

Who can explain the both result?

like image 886
wujunbin Avatar asked Sep 04 '26 14:09

wujunbin


1 Answers

I saw Dave Cheney tweet this the other day. My understanding is this:

First one - Dave's working one

The <number_here>: is an index in the array. This "sets" the current index.. which is why further into the declaration the index must be "reset" back in the array. So, the first number is 5 (index 0), the second "entry" has an index of 4: .. so the value 1 will be at index 4:

5 _ _ _ 1 _
         ^ index is currently here

..the next one has no index but it will continue after the last index given. which is 4+1 .. so index 5 gets the value 0:

5 _ _ _ 1 0
           ^ index is here.. it needs to be reset

Now the index will overrun .. so its gets set further back. The next one is 2: .. so that puts the value below with the value 3:

5 _ 3 _ 1 0
     ^ index is here

Next one again, continues on, since it has no index:

5 _ 3 2 1 0
       ^ index is here

Then the last one has index 1: .. with the value 4:

5 4 3 2 1 0

Second one - your broken one.

The second one is the same thing - but you haven't protected the over-writing of a currently placed index. Lets step through it:

Value 5 at index 0:

5 _ _ _ _ _ _ _ _
 ^ index is here

Value 1 at index 4:

5 _ _ _ 1 _ _ _ _
         ^ index is here

Value 0 at index 5 (remember, it continues on):

5 _ _ _ 1 0 _ _ _
           ^ index is here

Value 3 at index 2:

5 _ 3 _ 1 0 _ _ _
     ^ index is here

Value 2 at index 3 (again, it continues on:

5 _ 3 2 1 0 _ _ _
       ^ index is here

Value 4 at index 1:

5 4 3 2 1 0 _ _ _
   ^ index is here ... you're awfully close to overwriting the next value

Value 12 at index 2:

5 4 12 2 1 0 _ _ _
    ^^^^^ BOOOM

Boom..

..you've overwritten the value 3 and will continue to do so given where the index is for the remaining values. This is the problem..

like image 179
Simon Whitehead Avatar answered Sep 07 '26 07:09

Simon Whitehead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!