获得徽章 0
- golang的逃逸分析,很多博客说调用函数时参数是interface,数据就会逃逸到堆上,但我自己写的func,形参是interface,也没逃逸到堆上,那问题来了,fmt.Println()的时候,到底是什么原因导致了变量逃逸到堆上?
测试代码
```golang
func foo(i string) *string {
s := "jack_"+i
return &s
}
func main() {
word1 := foo("fmt print")
word2 := foo("myPrint")
word3 := foo("myPrintV2")
fmt.Println(*word1)
myPrint(*word2)
myPrintV2(*word3)
}
func myPrint(args ...interface{}) {
_ = args
}
func myPrintV2(arg interface{}) {
myPrint(arg)
}
```
结果: 只有fmt.Println()才发生逃逸了
```
./main.go:6:10: i does not escape
./main.go:7:2: moved to heap: s
./main.go:7:14: "jack_" + i escapes to heap
./main.go:23:14: args does not escape
./main.go:28:16: arg does not escape
./main.go:29:9: ... argument does not escape
./main.go:17:13: ... argument does not escape
./main.go:17:14: *word1 escapes to heap
./main.go:18:9: ... argument does not escape
./main.go:18:10: *word2 does not escape
./main.go:19:12: *word3 does not escape
```展开1点赞