dony113407 2018-12-12 12:32
浏览 39
已采纳

将项目附加到最大尺寸切片时附加行为

I'm confused about the behavior when appending to a slice which already has the max possible size.

As far as my understanding goes a slice can either have a max size of int32 or int64 depending on your system.

When executing test := make([]struct{},math.MaxInt64+1) I get the error len argument too large in make([]struct {}) which is within my expectations. But when doing something like:

test := make([]struct{},math.MaxInt64)
for i:=0;i<100 ; i++ {
    test = append(test, struct{}{})
}
fmt.Println(len(test))

I expect the program to panic but surprisingly the code runs with out any problems and len returns an overflowed value with -9223372036854775709.

Could someone maybe elaborate the behavior?

(I'm using go1.11.2 linux/amd64)

  • 写回答

1条回答 默认 最新

  • dswfyq6201 2018-12-12 13:09
    关注

    The spec says about length and capacity of any slice:

    At any time the following relationship holds:

    0 <= len(s) <= cap(s)
    

    This is clearly violated, as the length becomes negative, and thus less than 0. So this is a bug, already reported it and progress can be tracked here: https://github.com/golang/go/issues/29190

    Ian Lance Taylor confirms this is a bug and not how it should work. The proper behavior would be a panic saying growslice: cap out of range, which should originate from slice.go / growslice() function (growslice() is called from append()).

    If we slightly modify your example to this:

    s := make([]struct{}, math.MaxInt32-2)
    fmt.Println(len(s), cap(s))
    for i := 0; i < 5; i++ {
        s = append(s, struct{}{})
        fmt.Println(len(s), cap(s))
    }
    

    And run it on the Go Playground:

    2147483645 2147483645
    2147483646 2147483646
    2147483647 2147483647
    -2147483648 2147483647
    -2147483647 2147483647
    -2147483646 2147483647
    

    As we can see, the capacity stops growing once it reaches MaxInt32 on 32-bit architectures, and MaxInt64 on 64-bit architectures.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容