Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

Caller 返回在goroutine的函数调用栈上某个函数的源码所处在的文件位置及其行号

1
func Caller(skip int) (pc uintptr, file string, line int, ok bool)

skip为相对于Caller函数的位置,它用来在goroutine函数调用栈上定位目标函数 pc为 program counter

e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// /path/to/example.go
package main

import (
"fmt"
"runtime"
)

func a() {
b()
}

func b() {
c()
}

func c() {
pc, file, line, ok := runtime.Caller(2)
if ok {
fmt.Printf("pc: %v file: %v line: %v\n", pc, file, line)
}
}

func main() {
a()
}

该文件在调用Caller时,其goroutine的函数调用栈为:

    stack        skip

--> Caller        0
    c             1
    b             2
    a             3
    ....

栈顶的skip值为0(即Caller函数skip值总是0),skip值从栈顶到栈底逐渐增加。

因而例子中 skip=2 , 指的是调用b函数的位置, 其输出为

pc: 8276  file: /path/to/example.go line: 10