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 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路