I'm facing the error "panic: runtime error: makeslice: len out of range", while creating a dynamic array, for large values of length using "make()".
eg.
arr := make([]int, length) //length is a dynamic value
I know, this question was already asked here (Maximum length of a slice in Go). But, the make method does not support maximum value of the "int" datatype in golang. They consume the length value based on (size of) struct type. Is there any predefined APIs available to find maximum of the length value of a collection that can be declared in golang ?
Eg:
maxInt := int(^uint(0) >> 1)
arr := make([]struct{}, maxInt-1) //accepted
arr := make([]int, maxInt-1) //throw error
If you really want the max length of a slice, you can copy the algorithm used from the runtime package. This will take an example of the slice element to determine its size, and return the maximum slice capacity for that value type.
func maxSliceCap(i interface{}) int {
_64bit := uintptr(1 << (^uintptr(0) >> 63) / 2)
var goosWindows, goosDarwin, goarchArm64 uintptr
switch runtime.GOOS {
case "darwin":
goosDarwin = 1
case "windows":
goosWindows = 1
}
switch runtime.GOARCH {
case "arm64":
goarchArm64 = 1
}
heapMapBits := (_64bit*goosWindows)*35 + (_64bit*(1-goosWindows)*(1-goosDarwin*goarchArm64))*39 + goosDarwin*goarchArm64*31 + (1-_64bit)*32
maxMem := uintptr(1<<heapMapBits - 1)
elemSize := reflect.ValueOf(i).Type().Size()
max := maxMem / elemSize
if int(max) < 0 {
return 1<<31 - 1
}
return int(max)
}