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

标签 go aop

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

除了我在每个成员函数的开头使用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/

相关文章:

Golang 时间(分秒)

go - 意外的无效内存地址或 nil 指针取消引用

c# - 检查方法是否通过反射实现 IDisposable.Dispose

spring - 如何在没有接口(interface)的情况下使用加载时间编织配置 AspectJ

java - Spring AOP 命名切入点到底是如何工作的?有何用途?

go - 在新目录中打开 Shell

go - Docopt - Golang - 如何访问重复的参数?

go - 在 GORM 中与它自身的关系

java - spring boot中Aop的问题

java - 注释 Java 方法以记录其结果和异常