内容简介:如何获取golang中的函数的名字, 这里需要用到反射. 可以看如下代码.重点使用 runtime.FuncForPC 这个函数获取函数名.使用strings.FieldsFunc 对得到的带 路径名和包名的 函数名进行必要的处理.
如何获取golang中的函数的名字, 这里需要用到反射. 可以看如下代码.
重点使用 runtime.FuncForPC 这个函数获取函数名.
使用strings.FieldsFunc 对得到的带 路径名和包名的 函数名进行必要的处理.
package main
import (
"fmt"
"reflect"
"runtime"
"strings"
// "seps"
"runtime/debug"
)
func foo() {
}
func GetFunctionName(i interface{}, seps ...rune) string {
// 获取函数名称
fn := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
// 用 seps 进行分割
fields := strings.FieldsFunc(fn, func(sep rune) bool {
for _, s := range seps {
if sep == s {
return true
}
}
return false
})
// fmt.Println(fields)
if size := len(fields); size > 0 {
return fields[size-1]
}
return ""
}
func main() {
// This will print "name: main.foo"
fmt.Println("name:", GetFunctionName(foo))
// runtime/debug.FreeOSMemory
fmt.Println(GetFunctionName(debug.FreeOSMemory))
// FreeOSMemory
fmt.Println(GetFunctionName(debug.FreeOSMemory, '.'))
// FreeOSMemory
fmt.Println(GetFunctionName(debug.FreeOSMemory, '/', '.'))
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Little Schemer
[美] Daniel P. Friedman、[美] Matthias Felleisen / 卢俊祥 / 电子工业出版社 / 2017-7 / 65.00
《The Little Schemer:递归与函数式的奥妙》是一本久负盛名的经典之作,两位作者Daniel P. Friedman、Matthias Felleisen在程序语言界名声显赫。《The Little Schemer:递归与函数式的奥妙》介绍了Scheme的基本结构及其应用、Scheme的五法十诫、Continuation-Passing-Style、Partial Function、......一起来看看 《The Little Schemer》 这本书的介绍吧!