runtime.Caller

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

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. (For historical reasons the meaning of skip differs between Caller and Callers.) 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方法报告 在正在调用的gorountine堆栈上 有关函数调用的文件和行号.
参数skip是栈帧追踪的数量, 0表示Caller方法的调用方.
返回值报告相应调用的程序计数器、文件名和行号。如果无法恢复信息,则布尔值ok为false。

package main

import (
	"fmt"
	"runtime"
	"strconv"
)

func main() {
    
    
	f1()
}

func f1() {
    
    
	pc, file, line, ok := runtime.Caller(0)
	if !ok {
    
    
		fmt.Println("runtime.Caller() failed")
	}
	fmt.Println("name:"+runtime.FuncForPC(pc).Name())
	fmt.Println("file:"+file)
	fmt.Println("line",strconv.Itoa(line))
}

在这里插入图片描述
runtime.Caller(1)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45867397/article/details/121010671