douke6881 2015-10-03 17:20
浏览 74
已采纳

在Go中获取函数名称时,为什么会有“ -fm”后缀?

For the snippet below (runnable via the Go Playground),

package main

import (
  "fmt"
  "net/http"
  "reflect"
  "runtime"
)

type User struct{}

var u = &User{}

func (_ User) DummyHandler(w http.ResponseWriter, r *http.Request) {}

func funcName(i interface{}) {
  p := reflect.ValueOf(i).Pointer()
  n := runtime.FuncForPC(p).Name()
  fmt.Println(n)
}

func main() {
  funcName(u.DummyHandler)
}

The output is main.(User).DummyHandler-fm.

Why is there a -fm at the end of the function name?

  • 写回答

1条回答 默认 最新

  • dongxin991209 2015-10-03 17:20
    关注

    Turns out u.DummyHandler is a method value and the compiler implements methods by creating a function closure and modifying the function name. To quote Ian here:

    This seems to have become -fm on tip, by the way.

    Your code is getting a method value. p.beHappy is the beHappy method bound to the specific value of p. That is implemented by creating a function closure, and the code for that closure needs a name. The compiler happens to make that name by sticking fm on the end, but it could be anything that won't conflict with any other function name. There isn't any way to name that function in Go, so the name is irrelevant for anything other than the debugger or, as you see, FuncForPC.

    It seems like a better way to get a method's name is to reference the method directly, like so:

    func main() {
      funcName((User).DummyHandler)
    }
    

    This will output main.User.DummyHandler.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥20 win11无法启动 持续蓝屏且系统还原失败,无法开启系统保护
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码