dongxun7962 2011-05-03 11:42
浏览 325
已采纳

golang数组引用例如 b [1:4]引用元素1,2,3

The golang blog states :

"A slice can also be formed by "slicing" an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2)."

Can someone please explain to me the logic in the above. IE. Why doesn't b[1:4] reference elements 1 through 4? Is this consistent with other array referencing?

  • 写回答

4条回答 默认 最新

  • douxian1923 2011-05-03 13:22
    关注

    The reason is given in the Go Language Specification section on Slices.

    For a string, array, or slice a, the primary expression

        a[low : high]
    

    constructs a substring or slice. The index expressions low and high select which elements appear in the result. The result has indexes starting at 0 and length equal to high - low.

    For convenience, any of the index expressions may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.

    It's easy and efficient to calculate the length of the slice as high - low.

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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化