How to get path of imported package

前端 未结 2 454
天涯浪人
天涯浪人 2021-01-01 07:17

I\'m having difficulty when trying to get path of imported package. When I print result of os.Getwd() inside imported package, it\'s showing same path like on <

相关标签:
2条回答
  • 2021-01-01 07:35

    PkgPath() only can retrieve the package path for non-pointer

    // If the type was predeclared (string, error) or not defined (*T, struct{},
    // []int, or A where A is an alias for a non-defined type), the package path
    // will be the empty string.
    func packageName(v interface{}) string {
        if v == nil {
            return ""
        }
    
        val := reflect.ValueOf(v)
        if val.Kind() == reflect.Ptr {
            return val.Elem().Type().PkgPath()
        }
        return val.Type().PkgPath()
    }
    
    0 讨论(0)
  • 2021-01-01 07:48

    If you can get a reference to something in the package, you can use reflect to get the import path.

    Here's an example on Play:

    package main
    
    import (
        "bytes"
        "fmt"
        "reflect"
    )
    
    func main() {
        var b bytes.Buffer
        fmt.Println(reflect.TypeOf(b).PkgPath())
    }
    
    0 讨论(0)
提交回复
热议问题