duanfen2349 2017-05-31 04:01
浏览 738
已采纳

Golang:获取导入包的路径

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 main package.

This what I did.

Project structure

enter image description here

lib/lib.go

package lib

import "os"
import "fmt"

func init() {
    dir, _ := os.Getwd()
    fmt.Println("lib.init() :", dir)
}

func GetPath() {
    dir, _ := os.Getwd()
    fmt.Println("lib.GetPath() :", dir)
}

main.go

package main

import "os"
import "fmt"
import "test-import/lib"

func main() {
    dir, _ := os.Getwd()
    fmt.Println("main :", dir)
    lib.GetPath()
}

Result

lib.init() : /Users/novalagung/Documents/go/src/test-import
main : /Users/novalagung/Documents/go/src/test-import
lib.GetPath() : /Users/novalagung/Documents/go/src/test-import

The result of os.Getwd() from lib/lib.go is still same path like on main. What I want is the real path of the package which is /Users/novalagung/Documents/go/src/test-import/lib/

What should I do? Is it possible?

  • 写回答

1条回答 默认 最新

  • duanpao4522 2017-05-31 05:51
    关注

    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())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 webAPI接口返回值判断
  • ¥15 自动化测试 UI Automtion
  • ¥20 关于#深度学习#的问题:2708)输出:邻接矩阵A 或者 节点索引方式:通过随机游走或者其他方式,保持节点连接类似下图(语言-python)
  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?