dongzheng3113 2016-02-28 20:50
浏览 146
已采纳

重命名后导入Golang相对软件包

My $GOPATH is

"/Users/peter/goworkspace"

My current golang version:

go version go1.6 darwin/amd64

I have multiple golang projects under this workspace, so here is the the structure of directories

+/goworkspace  
  +---/bin  
  +---/pkg  
  +---/src  
    +---/project1
        +---package1 
           +---file1.go 
           +---file2.go 
           +---file3.go 
        +---package2 
        +---package3 
        +---main.go 
    +---/project2
    +---/project3

In my proj1's main.go, I will use the imports from other packages under this project, it will look like:

import(  
     "./package1"      
     "./package2"      
     "./package3"
 )  

however when I run "go build",I'm keeping getting error saying:
" can't load package: local import "../package" in non-local package

If I prefer not to use relative package path, for example use it like:

import(
    "project1/package1"  
    "project1/package2"   
    "project1/package3"   
)  

then everything will work.

What is wrong with my code if I use the relative package path?
And what is the best practice for package import if the project1's name will change in the future, for example it is changed to projecet1v2?
Do I need to manually update the imported package's name then?

  • 写回答

1条回答 默认 最新

  • douwen5690 2016-02-28 21:24
    关注

    Rule #1: Don't use relative imports. This is (partly) why you're running into issues. Read through this: https://golang.org/doc/code.html#Library

    Use the fully qualified import paths (as you showed):

    import(
        "project1/package1"  
        "project1/package2"   
        "project1/package3"
        // Or ideally, so others can access it in the future:
        "github.com/<yourusername>/project1/package4"
    )  
    

    If for some reason you want to version your package, you can either:

    • Provide a new repository (import URL)
    • Use a service like gopkg.in (http://labix.org/gopkg.in) to provide versioned import URLs (e.g. gopkg.in/you/pkgname.v2)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示