The array size, 1 << 30
, must be greater than or equal to any value of the length
variable.
package main
import (
"fmt"
"unsafe"
)
func main() {
type YourType byte
theCArray := &[8]YourType{}
const arrayLen = 1 << 30
{
length := arrayLen
fmt.Println()
fmt.Println(arrayLen, length)
fmt.Println()
slice := (*[arrayLen]YourType)(unsafe.Pointer(theCArray))[:length:length]
fmt.Println(len(slice), cap(slice), slice[:8])
}
{
length := arrayLen + 1
fmt.Println()
fmt.Println(arrayLen, length)
fmt.Println()
// runtime error: slice bounds out of range
slice := (*[arrayLen]YourType)(unsafe.Pointer(theCArray))[:length:length]
fmt.Println(len(slice), cap(slice), slice[:8])
}
}
Playground: https://play.golang.org/p/e4jv8jfU_WI
Output:
1073741824 1073741824
1073741824 1073741824 [0 0 0 0 0 0 0 0]
1073741824 1073741825
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.main()
/tmp/sandbox576164402/main.go:30 +0x320