Helpers for Go’s runtime package.
go get github.com/solsw/runtimehelper
import "github.com/solsw/runtimehelper"
The package provides two groups of helpers:
runtime.Func.Name) to just the package-qualified name or the bare function name.NthCallerName(n int) stringReturns the name of the n-th caller function of NthCallerName. On any failure an empty string is returned. The meaning of n matches runtime.Caller: 0 identifies NthCallerName itself, 1 its caller, and so on.
func work() string {
return runtimehelper.NthCallerName(1) // "...work" — work itself (the direct caller)
}
NthCallerName(2) from inside work would instead return the name of whoever called work.
CallerName() stringReturns the name of the function that called CallerName.
func work() {
name := runtimehelper.CallerName() // name of work's caller
_ = name
}
CallerCallerName() stringReturns the name of the function that called the function that called CallerCallerName (one frame further up than CallerName).
CallerNameandCallerCallerNameare marked//go:noinlineso they always occupy their own stack frame, keeping the fixed skip count passed toNthCallerNamecorrect.
These operate on the full function name string returned by runtime.Func.Name, e.g. "github.com/solsw/pkg.Foo".
JustPackageFunctionName(funcName string) stringReturns just the function name preceded by the package name. Generic type parameters (e.g. "[int]") are stripped.
| Input | Output |
|---|---|
github.com/solsw/pkg.Foo |
pkg.Foo |
github.com/solsw/pkg.Foo[int,string] |
pkg.Foo |
pkg.Foo |
pkg.Foo |
Foo |
Foo |
(empty) | (empty) |
JustFunctionName(funcName string) stringReturns just the function name. If funcName contains no package separator, it is returned (with generic type parameters stripped) unchanged.
| Input | Output |
|---|---|
github.com/solsw/pkg.Foo |
Foo |
github.com/solsw/pkg.Foo[int,string] |
Foo |
Foo |
Foo |
Foo[int] |
Foo |
(empty) | (empty) |
package main
import (
"fmt"
"github.com/solsw/runtimehelper"
)
func main() {
full := runtimehelper.NthCallerName(1) // "main.main"
fmt.Println(runtimehelper.JustPackageFunctionName(full)) // "main.main"
fmt.Println(runtimehelper.JustFunctionName(full)) // "main"
}