reflection - 为什么在 Go 中获取函数名时会有 "-fm"后缀?

标签 reflection go

对于下面的代码片段 ( 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)
}

输出是 main.(User).DummyHandler-fm

为什么函数名后面有一个-fm

最佳答案

原来 u.DummyHandler 是一个方法值,编译器通过创建一个函数闭包并修改函数名来实现方法。引用伊恩 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.

获取方法名称的更好方法似乎是直接引用该方法,如下所示:

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

这将输出 main.User.DummyHandler

关于reflection - 为什么在 Go 中获取函数名时会有 "-fm"后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925344/

相关文章:

c# - 如何获得一个 System.Collections.Generic.List<FieldInfo> ,它包含类型 T 对象的所有 FieldInfo,直到类层次结构中的对象?

json - 在读取 json 数据时动态识别对象的类型

c# - 从其他属性的代码中测试属性

go - 不清楚种族状况的原因

戈朗 : Make select statemet deterministic?

arrays - 使用 pgx 使用 JSONBArray 时出现 "wrong element type"

c# - 动态 List<T>.Add 抛出 RuntimeBinderException

c# - 反射基础知识

go vet 警告 example 指的是未知标识符,但为什么呢?

在 Linux 上绘制 Golang OpenGL 线,但在 Windows10 上不绘制