douzhanhui5662 2014-11-12 12:33
浏览 73
已采纳

如何在golang中的一个存储库下在彼此之间导入软件包?

I want to understand how to import packages correctly in the example beyond.

I've read this topic (How to use custom packages in golang?), but it doesn't explain what I'm trying to understand.

For example, I want to create package for further using it in my program and publishing at github.com. This is how the code should be organized in my view:

src/
  github.com/
    username/
      repository/
        lib1.go #package repository
        lib2.go #package repository
        sublib/
          sublib1.go #package sublib
          sublib2.go #package sublib
      ...

  myproject/
    programname.go #package main
    #there is no problem how to import my repository here:
    #import "github.com/username/repository"
    #or import "github.com/username/repository/sublib" 

Ok, at this point I want to understand how can I import repository's code in the repository/sublib and vise versa. I think question is more aimed for internal importing (under one repository).

First solution is obviously - importing packages by fullpath:

  • github.com/username/repository in sublib1.go and
  • github.com/username/repository/sublib in lib1.go

Hmm, but what if I change path in the future? May be there is better way for importing internal packages.. Also I'm faced with a problem when I import github.com/username/repository in the sublib1.go (I get the error message import cycle not allowed).

I hope I've explained quite ok to get this question.

  • 写回答

2条回答 默认 最新

  • duanjian5059 2014-11-12 12:52
    关注

    import "github.com/username/repository/sublib" is the way to go: as I mentioned in "Is it possible don't specify package name?", the other "solution" would be

    import "./sublib"
    

    That is using a relative path, which is not considered a good practice, as explained in "Go language package structure" and "Golang how to import local packages without gopath?".

    If you change path in the future, the issue will be similar with absolute or relative import paths, but the first (absolute) paths remains "go-gettable" by other people.

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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题