dqwh1209 2013-07-09 03:28
浏览 525
已采纳

如何不使用gopath导入本地软件包

I've used GOPATH but for this current issue I'm facing it does not help. I want to be able to create packages that are specific to a project:

myproject/
├── binary1.go
├── binary2.go
├── package1.go
└── package2.go

I tried multiple ways but how do I get package1.go to work in the binary1.go or the binary2.go and so on?

For example; I want to be able to import "package1" and then be able to run go build binary1.go and everything works fine without the error being thrown that the package cannot be found on GOROOT or GOPATH. The reason why I need this kind of functionality is for large scale projects; I do not want to have to reference multiple other packages or keep them in one large file.

  • 写回答

5条回答 默认 最新

  • duanleiliu7373 2013-07-09 03:43
    关注

    Go dependency management summary:

    • vgo if your go version is: x >= go 1.11
    • dep or vendor if your go version is: go 1.6 >= x < go 1.11
    • Manually if your go version is: x < go 1.6

    Edit 3: Go 1.11 has a feature vgo which will replace dep.

    To use vgo, see Modules documentation. TLDR below:

    export GO111MODULE=on
    go mod init
    go mod vendor # if you have vendor/ folder, will automatically integrate
    go build
    

    This method creates a file called go.mod in your projects directory. You can then build your project with go build. If GO111MODULE=auto is set, then your project cannot be in $GOPATH.


    Edit 2: The vendoring method is still valid and works without issue. vendor is largely a manual process, because of this dep and vgo were created.


    Edit 1: While my old way works it's not longer the "correct" way to do it. You should be using vendor capabilities, vgo, or dep (for now) that are enabled by default in Go 1.6; see. You basically add your "external" or "dependent" packages within a vendor directory; upon compilation the compiler will use these packages first.


    Found. I was able import local package with GOPATH by creating a subfolder of package1 and then importing with import "./package1" in binary1.go and binary2.go scripts like this :

    binary1.go

    ...
    import (
            "./package1"
          )
    ...
    

    So my current directory structure looks like this:

    myproject/
    ├── binary1.go
    ├── binary2.go
    ├── package1/
    │   └── package1.go
    └── package2.go
    

    I should also note that relative paths (at least in go 1.5) also work; for example:

    import "../packageX"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!