mirror of https://github.com/rwxrob/bonzai
Add util.FuncName
parent
fe9dec48d4
commit
bed5d82c50
@ -0,0 +1,17 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FuncName makes a best effort attempt to return the string name of the
|
||||
// passed function. Anonymous functions are named "funcN" where N is the
|
||||
// order of appearance within the current scope. Note that this function
|
||||
// will panic if not passed a function.
|
||||
func FuncName(i any) string {
|
||||
p := runtime.FuncForPC(reflect.ValueOf(i).Pointer())
|
||||
n := strings.Split(p.Name(), `.`)
|
||||
return n[len(n)-1]
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package util_test
|
||||
|
||||
import (
|
||||
"github.com/rwxrob/bonzai/each"
|
||||
"github.com/rwxrob/bonzai/fn"
|
||||
"github.com/rwxrob/bonzai/util"
|
||||
)
|
||||
|
||||
func Foo() {}
|
||||
|
||||
func ExampleFuncName() {
|
||||
|
||||
f1 := func() {}
|
||||
f2 := func() {}
|
||||
|
||||
// Foo is defined outside of the ExampleFuncName
|
||||
|
||||
each.Println(fn.Map([]any{f1, f2, Foo, util.Files}, util.FuncName))
|
||||
|
||||
// Output:
|
||||
// func1
|
||||
// func2
|
||||
// Foo
|
||||
// Files
|
||||
}
|
Loading…
Reference in New Issue