duanji9264 2018-01-30 10:11
浏览 28
已采纳

将一个主程序包放在cmd / myapp子目录中可以吗?

this is my first Go project and I have had a hard time grasping the different documents on code organization (e.g. I found it somewhat hard to tell which ones have been superceded, or apply to deprecated vendoring tools/approaches). I finally settled on Ben Johnson's Standard Package Layout, with a very slim root package (in the root directory of my project) and most code in internal/pkg/...

However, I've added a cmd/myapp dir and put my main.go file for the executable program in there, since I understood that to be a common pattern.

So now I have:

myapp
|
+- myapp.go   // "package myapp", with only type and interface declarations and no imports
|
+- cmd
|   |
|   +- main.go // "package main", with import gitlab.tld/username/myapp, gitlab.tld/username/myapp/internal/pkg/routing etc.
|
+- internal
    |
    +- pkg
        |
        +- routing
        |    |
        |    +- routing.go // "package routing"
        |
        +- sql 
        |
        +- etc.

Now, when I go to cmd/myapp and call go build, it builds fine and leaves an executable that does what it's supposed to do right there. But when I call go build -v from the project's main directory, no executable is produced. In fact, only myapp.go seems to be processed which contains only type definitions. (And of course, go install does not produce a binary either. go get -v gitlab.tld/username/myapp also does not seem to do anything.)

So I have the suspicion that this is not how it is meant after all, but I am not even so sure about that. Is there a problem with the project layout, or did I get the usage of go tooling wrong?

Thanks for any help you might provide to this go newbie,

Andreas

  • 写回答

1条回答 默认 最新

  • dongzhao8233 2018-01-30 10:59
    关注

    When you run go build or go install the command expects a list of packages to process. If no import paths are given, the action applies to the package in the current directory.

    So if there is no package main in your root directory, no executable will be produced.

    The command doesn't look in subdirectories. You may have multiple commands in your cmd directory. In this case it won't know which one to build. And building all of them every time is wasteful.

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

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗