doudaifu6083 2014-09-08 01:35
浏览 38
已采纳

关于golang数组

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?

  • 写回答

2条回答 默认 最新

  • douluan1533 2014-09-08 01:58
    关注

    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..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?