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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器