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.
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