---
# System prepended metadata

title: Runtime Caller
tags: [Go]

---

Runtime Caller
==========================
###### tags: `Go`

log時常常會需要function被誰調用, 有便於知道調用的上下文

## func Caller[^2]
```
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
```
caller會回傳檔案路徑 行數 跟stack中的調用方法名稱
skip用來決定stack裡的元素要被跳過多少層; 0就表示只回傳caller自己 
```go=
import (
    "fmt"
    "runtime"
)

func main() {
    for i:=0 ;i<5; i++{
        test(i)
    } 
}

func test(skip int){
    call(skip)
}

func call(skip int){
    pc, file, line, ok := runtime.Caller(skip)
    pcName := runtime.FuncForPC(pc).Name()
    fmt.Println(fmt.Sprintf("%v %s %d %t %s",pc,file,line,ok,pcName))
}
```


[^1]: [Go package Runtime](https://pkg.go.dev/runtime#section-documentation)

[^2]: [Func Caller](https://pkg.go.dev/runtime#Caller)