dsirr48088
2017-07-17 00:01
浏览 182
已采纳

如何在golang中进行简短/相对导入?

Is it possible to make a relative import in go code? I read a lot of examples but I really can't understand how to make it. For example, I have a project app and a sub package utils in it.

app
   main.go
   utils
        utils.go

utils.go:

package utils

import "fmt"

func TestFunc()  {
    fmt.Print("I'm a TestFunc")
}

Is there a way to import this package using only import "./utils" or import "app/utils but not take all the path like import "github.com/hithubuser/app/utils"?

If there is no way to do it, how do you work with the nested packages? Do you write a full the path for all the imports or you avoid to make it?

图片转代码服务由CSDN问答提供 功能建议

是否可以在go代码中进行相对导入? 我读了很多例子,但我真的不明白如何做到这一点。 例如,我有一个项目 app 和一个子包 utils

  app 
 main.go  
 utils 
 utils.go 
   
 
 

utils.go:

  package utils 
 
import“  fmt“ 
 
func TestFunc(){
 fmt.Print(”我是TestFunc“)
} 
   
 
 

是否可以导入 该软件包仅使用 import“ ./utils” import“ app / utils ”,但不采用 import” github.com/hithubuser/app/ utils“

如果没有办法,如何使用嵌套包?您为所有导入编写完整路径还是避免使用 做到吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglian8407 2017-07-17 00:20
    已采纳

    Typically import path starts after $GOPATH/src, refer to doc.

    Let's say you have directory structure:

    $GOPATH/src/github.com/hithubuser/app/utils
    
    # your import path is 'github.com/hithubuser/app/utils'
    

    Do you write a full the path for all the imports or you avoid to make it?

    Yes, generally full import is used, since it enables you to distribute your code as go library. So that you can develop reusable code and import it in any project as needed or you can publish it to Go community.


    Let's say you have standalone project, not referred to any other Go project and you're distributing as binary instead of go library. Then you can to something like this (it is not commonly used/recommended though).

    Just git clone your repo at $GOPATH/src like git clone github.com/hithubuser/app

    $GOPATH/src/app/utils
    
    # then import path is app/utils
    
    打赏 评论
  • ds2321 2017-07-17 00:42

    Another possibility is to use the vendor facilities introduced in Go 1.5.

    1. Create a vendor directory.
    2. Copy (or git clone or whatever) your utils directory as a subdirectory of vendor, so your hierarchy now looks like this:

      app
      |-- main.go
      `-- vendor/
          `-- utils/
              `-- utils.go
      
    3. Set the GO15VENDOREXPERIMENT environment variable to 1 to enable vendoring support if you're using Go 1.5. Newer versions enable it by default.

    打赏 评论

相关推荐 更多相似问题