Go中切片的最大长度

Go中切片的最大长度,go,slice,Go,Slice,我在4Gb机器的64位linux操作系统中运行了以下代码: package main import ( "fmt" "math" ) func main() { r := make([]bool, math.MaxInt32) fmt.Println("Size: ", len(r)) } 当我运行此命令时,我得到: Size: 2147483647 如果我更改math.MaxInt32的math.MaxInt32,我会得到: fatal error:

我在4Gb机器的64位linux操作系统中运行了以下代码:

package main

import (
    "fmt"
    "math"
)

func main() {
    r := make([]bool, math.MaxInt32)

    fmt.Println("Size: ", len(r))
}
当我运行此命令时,我得到:

Size: 2147483647
如果我更改
math.MaxInt32的
math.MaxInt32
,我会得到:

fatal error: runtime: out of memory
panic: runtime error: makeslice: len out of range
片大小为
math.maxint32
时,我的内存用完了,这是我所期望的,但当我尝试使用
math.MaxInt64
时,我得到:

fatal error: runtime: out of memory
panic: runtime error: makeslice: len out of range
因此,我很可能无法创建一个大小为
math.MaxInt64
的切片,这就引出了我的问题:如果内存不是问题,我在Go中无法创建的最大切片是什么

我记得,在Java中,原始数组索引是用
int
类型管理的,因此原始数组的最大大小是
int
的最大值,如果您尝试使用
long
执行此操作,它将引发异常(据我所记得的),Go也是这样吗?Go中的切片索引是否绑定到一个特定类型

编辑:

我使用
struct{}
而不是
bool
运行测试,并分配
math.MaxInt64
元素。一切如期进行,并打印:

Size: 9223372036854775807
那么,另一个问题是,当错误看起来是相同的(内存不足)时,为什么会有两条不同的错误消息


每个错误弹出的条件是什么?

根据文档,
元素可以通过整数索引0到len(s)-1来解决。这意味着片的最大容量是目标构建上默认整数的大小

编辑:从源代码看,似乎有一个安全检查,以确保切片的大小是可能的:

func makeslice(t *slicetype, len64 int64, cap64 int64) sliceStruct {
    // NOTE: The len > MaxMem/elemsize check here is not strictly necessary,
    // but it produces a 'len out of range' error instead of a 'cap out of range' error
    // when someone does make([]T, bignumber). 'cap out of range' is true too,
    // but since the cap is only being supplied implicitly, saying len is clearer.
    // See issue 4085.
    len := int(len64)
    if len64 < 0 || int64(len) != len64 || t.elem.size > 0 && uintptr(len) > maxmem/uintptr(t.elem.size) {
        panic(errorString("makeslice: len out of range"))
    }

我确信我运行64位Go,如果我运行
Go版本
它会打印
Go版本go1.4 linux/amd64
@SimonOroño什么是
Go环境
print for GOARCH?@SimonOroño我已经看过了Go的源代码,我想我知道这个问题。更新我的答案。amd64。我使用struct{}运行测试,并且必须更新问题。请检查:-)@Not_a_Golferwell,如果进行了检查,那么我如何获得
致命错误:运行时:内存不足
使用
bool
math.maxint32
?因此,这似乎是错误消息不明确的问题,仅此而已……)