gpt4 book ai didi

戈朗 : How to run the same logic at the beginning of every struct member functions?

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:34 26 4
gpt4 key购买 nike

例如,我想打印出某个结构的每个函数的函数名。

除了我在每个成员函数的开头使用fmt.Println,还有什么更好的方法吗?

最佳答案

package main

import "fmt"
import "runtime"

func main() {
pc, _, _, _ := runtime.Caller(0)
fmt.Println("Name of function: " + runtime.FuncForPC(pc).Name())
fmt.Println()

// or, define a function for it
fmt.Println("Name of function: " + funcName())
x()
}

func funcName() string {
pc, _, _, _ := runtime.Caller(1)
return runtime.FuncForPC(pc).Name()
}

func x() {
fmt.Println("Name of function: " + funcName())
y()
}

func y() {
fmt.Println("Name of function: " + funcName())
z()
}
func z() {
fmt.Println("Name of function: " + funcName())
}

Output:

Name of function: main.main

Name of function: main.main
Name of function: main.x
Name of function: main.y
Name of function: main.z

(here 复制)

关于戈朗 : How to run the same logic at the beginning of every struct member functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34848961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com