douwen5584 2014-05-11 15:38
浏览 234
已采纳

从Go中的main导入本地包

I'm writing an API using Go and its net/http stdlib module and i have some utils code in a directory named utils. But when i import them in main, Go does not find the packages. The root cause is apparently the fact that Go packages have to be saved in $GOPATH/src/. So i wanted to know if there was a way to import local packages and save them in the same folder as the main package.

I'm following the Github Directory Structure so my $GOPATH looks like that.

$GOPATH/src/
   |___github.com/
       |___user/
           |___repository/
               |___main.go
               |___utils/
                   |___core.go
                   |___factory.go

As the utils directory is really tied to the app, it would be really bad for me to save it as a different Go app in $GOPATH/src. And apart from that, imagine the moment when i will want to push my code on Github. Here it's only 2 repositories but if it was 6 i would need 6 private repos for really related and tied parts of a single application.

  • 写回答

1条回答 默认 最新

  • doupo5178 2014-05-12 01:31
    关注

    (Documenting an answer as it looks unanswered at first glance)

    The package declaration on both files should be package utils and they should be imported with:

    import "github.com/user/repository/utils"
    

    Its also possible to make sub-packages (standard library io package has io/ioutil) if you really want to separate each code file as separate packages.

    import "github.com/user/repository/utils"
    import "github.com/user/repository/utils/sub"
    

    The local directory structure would be:

    $GOPATH/src/
       |___github.com/
           |___user/
               |___repository/
                   |___main.go
                   |___utils/
                       |___core.go
                       |___sub/factory.go
    

    (Answer details posted in comment by @phndiaye)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog