运行时出现了错误或者调试过程需要了解堆栈内容时,需要打印出堆栈的信息。
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println(stack())
}
func stack() string {
var buf [2 << 10]byte
return string(buf[:runtime.Stack(buf[:], true)])
}
输出结果
qxcs-MacBook-Pro% go run test.go
goroutine 1 [running]:
main.stack(0x0, 0xc42003bf68)
/Users/qxc/work/test/test.go:14 +0x5b
main.main()
/Users/qxc/work/test/test.go:9 +0x26