douza1373 2016-01-15 12:32
浏览 422
已采纳

我可以在golang的for-range迭代中使索引为int64吗?

According to the spec the

for idx, val range a_slice 

statement returns idx as an integer.

Since creating a large size slice is possible, is there a way to chance idx to int64?

Thank you.

  • 写回答

1条回答 默认 最新

  • dongzhucha3999 2016-01-15 12:47
    关注

    No, the spec specifies the type of index to be int if you use a "for" statement with a "range" clause:

    Range expression                          1st value          2nd value
    
    array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
    string          s  string type            index    i  int    see below  rune
    map             m  map[K]V                key      k  K      m[k]       V
    channel         c  chan E, <-chan E       element  e  E
    

    Nothing you can do about it, and nothing you should do about it. The length of the slice/array will fit into int.

    It is not possible to make a slice bigger than max int. Attempting to make a larger slice with a constant expression is a compile-time error:

    x := make([]struct{}, 3123456789)
    

    Compile-time error: len argument too large in make([]struct {})

    Note: size of int is implementation-specific: it is either 32-bit or 64-bit. The constant expressions here to produce the errors are for 32-bit ints (the Go Playground uses 32-bit ints).

    If length is a runtime expression, it panics:

    i := uint(3123456789)
    y := make([]struct{}, i)
    

    Runtime error: panic: runtime error: makeslice: len out of range

    And length of array types must also fit into int: Spec: Array types:

    The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int.

    Attempting to use a larger length is a compile-time error:

    var x [3123456789]struct{}
    type t1 [3123456789]byte
    type t2 [3123456789]struct{}
    

    All compile-time error: array bound is too large

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!