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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀