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

如何在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?

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号