$ go version
go version go1.14.1 windows/amd64
$ cat test.go
package main
func main() {
i := 2
s := make([]int, 2, 3)
s = make([]int, i, 3)
s = make([]int, i, 1)
s[0] = 1
}
$ go run -gcflags -m=2 test.go
# command-line-arguments
.\test.go:3:6: can inline main as: func() { i := 2; s := make([]int, 2, 3); s = make([]int, i, 3); s = make([]int, i, 1); s[0] = 1 }
.\test.go:6:10: make([]int, i, 3) escapes to heap:
.\test.go:6:10: flow: {heap} = &{storage for make([]int, i, 3)}:
.\test.go:6:10: from make([]int, i, 3) (non-constant size) at .\test.go:6:10
.\test.go:7:10: make([]int, i, 1) escapes to heap:
.\test.go:7:10: flow: {heap} = &{storage for make([]int, i, 1)}:
.\test.go:7:10: from make([]int, i, 1) (non-constant size) at .\test.go:7:10
.\test.go:5:11: make([]int, 2, 3) does not escape
.\test.go:6:10: make([]int, i, 3) escapes to heap
.\test.go:7:10: make([]int, i, 1) escapes to heap
panic: runtime error: makeslice: cap out of range
goroutine 1 [running]:
main.main()
C:/cygwin64/home/work/projects/test/test.go:7 +0x68
exit status 2
In this program, the compiler's escape analysis judges that the array allocated by make escapes to the heap, when len is variable. But actually this array can be allocated on stack because we can't make len greater than cap in runtime and cap is constant.
In this program, the compiler's escape analysis judges that the array allocated by make escapes to the heap, when
lenis variable. But actually this array can be allocated on stack because we can't makelengreater thancapin runtime andcapis constant.