英文:
Can I make the index int64 in golang's for-range iteration?
问题
根据规范,for idx, val range a_slice
语句中的idx
返回的是一个integer
类型。由于可以创建大尺寸的切片(slice),是否有办法将idx
更改为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
得分: 12
不,如果你在使用“for”语句和“range”子句时,规范指定索引类型为int
:
范围表达式 第一个值 第二个值
数组或切片 a [n]E, *[n]E, 或 []E 索引 i int a[i] E
字符串 s 字符串类型 索引 i int 见下文 rune
映射 m map[K]V 键 k K m[k] V
通道 c chan E, <-chan E 元素 e E
你无法改变它,也不应该改变它。切片/数组的长度将适应int
。
无法创建比最大int
更大的切片。尝试使用常量表达式创建更大的切片会导致编译时错误:
x := make([]struct{}, 3123456789)
编译时错误:len argument too large in make([]struct {})
注意:int
的大小是与具体实现相关的:它可以是32位或64位。这里产生错误的常量表达式是针对32位int
的(Go Playground使用32位int
).
如果长度是运行时表达式,会引发恐慌:
i := uint(3123456789)
y := make([]struct{}, i)
运行时错误:panic: runtime error: makeslice: len out of range
数组类型的长度也必须适应int
:规范:数组类型
> 长度是数组类型的一部分;它必须评估为一个非负的常量,可以由int
类型的值表示。
尝试使用更大的长度会导致编译时错误:
var x [3123456789]struct{}
type t1 [3123456789]byte
type t2 [3123456789]struct{}
所有的编译时错误:array bound is too large
英文:
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 int
s (the Go Playground uses 32-bit int
s).
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论