반응형
How to get the name of a function in Go?
Given a function, is it possible to get its name? Say:
func foo() {
}
func GetFunctionName(i interface{}) string {
// ...
}
func main() {
// Will print "name: foo"
fmt.Println("name:", GetFunctionName(foo))
}
I was told that runtime.FuncForPC would help, but I failed to understand how to use it.
Sorry for answering my own question, but I found a solution:
package main
import (
"fmt"
"reflect"
"runtime"
)
func foo() {
}
func GetFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func main() {
// This will print "name: main.foo"
fmt.Println("name:", GetFunctionName(foo))
}
Not exactly what you want, because it logs the filename and the line number, but here is how I do it in my Tideland Common Go Library (http://tideland-cgl.googlecode.com/) using the "runtime" package:
// Debug prints a debug information to the log with file and line.
func Debug(format string, a ...interface{}) {
_, file, line, _ := runtime.Caller(1)
info := fmt.Sprintf(format, a...)
log.Printf("[cgl] debug %s:%d %v", file, line, info)
참고URL : https://stackoverflow.com/questions/7052693/how-to-get-the-name-of-a-function-in-go
반응형
'program tip' 카테고리의 다른 글
[]를 사용할 때 C ++ 맵 유형 인수에 빈 생성자가 필요한 이유는 무엇입니까? (0) | 2020.09.12 |
---|---|
When, if ever, is loop unrolling still useful? (0) | 2020.09.12 |
Java에서 Ordered Set 구현이 있습니까? (0) | 2020.09.12 |
Rails는 데이터베이스에 대해 실행 된 마이그레이션을 어떻게 추적합니까? (0) | 2020.09.12 |
UIButton에서 네이티브 "펄스 효과"애니메이션을 수행하는 방법-iOS (0) | 2020.09.11 |