仅从Go中的函数引用获取接收器类型和方法名称

时间:2018-11-28 08:43:29

标签: go

给出这样的代码设置,

package main

import (
    "fmt"
    "reflect"
    "runtime/debug"
)

type A struct{}

func (o *A) B() error {
    debug.PrintStack()
    return nil
}

func main() {
    a := &A{}
    b := a.B

    // Note that if run b(), it can print the stack and show the info 
    // "(*A).B-fm" and "(*A).B"

    m := reflect.ValueOf(b)
    fmt.Println(m.Type().String())
}

是否可以通过方法获取 b 的接收器类型A和B的信息?如果可能怎么办?

请注意, b 是类型A的方法B的值。

(可能的使用情况,通过形成类似(* A).B 的字符串,仅基于b这样的引用来生成恒定的唯一API ID。它用于构建不带a的调试工具需要更改现有代码。)

更新:

1 个答案:

答案 0 :(得分:2)

这将完成工作。

fmt.Println(runtime.FuncForPC(m.Pointer()).Name())

awesome article的信用额