douwen5546 2013-01-11 18:25
浏览 41
已采纳

我可以使用同名的库和二进制文件吗?

I'm building a library, but I also want it to be usable as a standalone binary.

For example, let's say I'm building an implementation of Tar. Tar is commonly used as a command, but it can also be used as a library. Intuitively, I'd do something like this:

src/
    tar/
        tar.go # belongs to package tar
        main.go # imports tar and provides a main function

This doesn't seem to work though. From the documentation, it seems that "commands" should have a separate name from the library. Adapting the example given there to this example, I have the following directory structure:

src/
    tar/
        tar.go # belongs to package tar
    tarbin/
        main.go # imports tar and provides a main function

However, this creates a command called tarbin, not tar in $GOPATH/bin. The workaround I've found is to do go build -o $GOPATH/bin/tar tar, but I get the feeling I'm doing something horribly wrong. Is there a better way?

Note: I'm well aware that tar is included in the standard libs, I'm only using it as an example.

  • 写回答

1条回答 默认 最新

  • doubinchou4219 2013-01-11 18:38
    关注

    I'd probably do this

    src/
        tar/
            tar.go         # tar libary
            tar/
                main.go    # tar binary
    

    That will give you a binary called tar and a library called tar

    Let's say you are hosting this on github then you'd want

    src/
        github.com/
            you/
                tar/
                    tar.go         # tar libary
                    tar/
                        main.go    # tar binary
    

    Which would give you a binary called tar when you do go get install github.com/you/tar/tar and a library called github.com/you/tar when you do go get install github.com/you/tar

    Depending on which you feel is more important you could swap the library and the binary over

    src/
        github.com/
            you/
                tar/
                    main.go            # tar binary
                    tar/
                        tar.go         # tar libary
    

    Keeping all the code in one tree enables you to do go install ./... from the root to build all packages and subpackages which is an advantage. go test|fmt ./... also. (Note that really is 3 dots!)

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题