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

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?