1 回答
TA贡献1827条经验 获得超7个赞
根据文档,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
- 1 回答
- 0 关注
- 258 浏览
添加回答
举报