51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

runtime.Caller (go 获取 文件名 路径)

获取 go 执行代码的 文件名, 以及路径的方法:

package main

import (
	"fmt"
	"path"
	"runtime"
)

func getInfo(n int) {
	pc, file, line, ok := runtime.Caller(n)
	if !ok {
		fmt.Println("runtime.caller() failed\n")
		return

	}
	funcName := runtime.FuncForPC(pc).Name()
	fmt.Println("-------------")
	fmt.Println(funcName)
	fmt.Println(file)
	fmt.Println(path.Base(file)) // 获取文件名
	fmt.Println(line)

}
func f2() {
	getInfo(0) // 获取函数名,  用 0,1,2  多测试一下
}

func main() {
	f2()

}

结果:

赞(0)
未经允许不得转载:工具盒子 » runtime.Caller (go 获取 文件名 路径)