您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Go中切片的最大长度

Go中切片的最大长度

根据文档,The elements can be addressed by integer indices 0 through 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"))
    }

因此,在这种情况下,看起来uintptr(len) > maxmem/uintptr(t.elem.size)我们不允许这样做。

但是,当我分配struct{}不占用内存的空间时,将允许该大小:

func main(){
    r := make([]struct{}, math.MaxInt64)
    fmt.Println(len(r))
}
// prints 9223372036854775807
Go 2022/1/1 18:15:39 有543人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶