有的时候需要在程序运行中打印当前package name,比如一些log系统,在每条log中希望打印出是在哪个pkg内(当然打印文件名也是可以的)。网上找了找,基本上也是先用runtime找到调用文件,然后通过path.Dir来找上级文件夹名,虽然也可以,但是总觉有点“取巧”。见:https://stackoverflow.com/questions/32163425/golang-how-to-get-the-directory-of-the-package-the-file-is-in-not-the-current-w
其实可以利用反射,见https://stackoverflow.com/questions/25262754/how-to-get-name-of-current-package-in-go:
package myPkg
import (
"fmt"
"reflect"
)
func DumpMyName(){
type em struct{}
fmt.Println(reflect.TypeOf(em{}).PkgPath())
}