dsgdhf5674 2016-11-11 08:07
浏览 53
已采纳

转到项目结构以在单个存储库中产生具有相同名称的库和cli

How to setup project structure to produce library and cli with same name in single repository?

Suppose my project name is project. I want to make it importable with name project and have executable binary with name project when installed with go get. My setup currently is like this:

host.com/project/
    project/
        main.go
    core/
        project.go

Then, when installed with:

go get host.com/project/project

it installs project as executable which pulls core as dependency. In core/project.go file, the package has this:

package project

The problem is it is imported with:

import (
    "host.com/project/core"
)

And it exports project as name space not core which violates go's convention. How can I do this?

  • 写回答

1条回答 默认 最新

  • dtqie02844 2016-11-11 08:14
    关注

    This isn't a convention, and you may do however you like, but it's a common practice to have a cmd folder in the project root, and all the executables go under that, each in is own folder.

    So a good solution in your case could be simply:

    host.com/project/
        cmd/
            project/
                project.go
        filea.go
        fileb.go
    

    In filea.go and fileb.go the package declaration should be:

    package project
    

    In cmd/project/project.go package and import declaration should be:

    package main
    
    import "host.com/project"
    

    Of course if your project is more complex, you may create further packages under the project root, and it may have multiple commands (multiple main packages), e.g.:

    host.com/project/
        cmd/
            project/
                project.go
            prjtool/
                prjtool.go
        packagex/
            x.go
        packagey/
            y.go
        filea.go
        fileb.go
    

    An example following this layout is the very popular Go Delve debugger (4.5k stars currently), available at https://github.com/derekparker/delve.

    A very complex repository example is the golang.org/x/tools package which is a collection of multiple, essential Go tools, available at https://github.com/golang/tools/. Its cmd folder contains more than 20 subfolders (commands), many of the tools (main packages) even consist of multiple .go files (but each using package main declaration, forming a single package of the executable).

    Also check out the following related question: What is a sensible way to layout a Go project

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

报告相同问题?

悬赏问题

  • ¥40 图书信息管理系统程序编写
  • ¥15 7-1 jmu-java-m02-使用二维数组存储多元线性方程组
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题