Get name of function using reflection

前端 未结 3 1788
孤街浪徒
孤街浪徒 2020-12-25 14:06

I\'m trying to use Go\'s reflection system to retrieve the name of a function but I get an empty string when calling the Name method on its type. Is this the expected behavi

3条回答
  •  长发绾君心
    2020-12-25 14:11

    import runtime
    
    func funcName() string {
        pc, _, _, _ := runtime.Caller(1)
        nameFull := runtime.FuncForPC(pc).Name()    // main.foo
        nameEnd := filepath.Ext(nameFull)           // .foo
        name := strings.TrimPrefix(nameEnd, ".")    // foo
        return name
    }
    

提交回复
热议问题