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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动