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 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题