我可以拥有同名的库和二进制文件吗? [英] Can I have a library and binary with the same name?

查看:29
本文介绍了我可以拥有同名的库和二进制文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个库,但我也希望它可以作为独立的二进制文件使用.

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

例如,假设我正在构建 Tar 的实现.Tar 通常用作命令,但也可以用作库.直觉上,我会做这样的事情:

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

虽然这似乎不起作用.从 documentation 来看,命令"似乎应该有一个与库不同的名称.将那里给出的例子改编为这个例子,我有以下目录结构:

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

然而,这会在 $GOPATH/bin 中创建一个名为 tarbin 的命令,而不是 tar.我发现的解决方法是执行 go build -o $GOPATH/bin/tar tar,但我觉得我在做一些非常错误的事情.有没有更好的办法?

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?

注意:我很清楚tar包含在标准库中,我只是将其用作示例.

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

推荐答案

我可能会这样做

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

这会给你一个名为 tar 的二进制文件和一个名为 tar

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

假设您将它托管在 github 上,然后您会想要

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

当你执行 go get install github.com/you/tar/tar 和一个名为 github.com/you/tar 的库时,它会给你一个名为 tar 的二进制文件> 当你做 go get install github.com/you/tar

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

将所有代码保存在一棵树中使您能够从根目录执行 go install ./... 以构建所有包和子包,这是一个优势.go test|fmt ./... 也是.(注意,真的是 3 个点!)

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

这篇关于我可以拥有同名的库和二进制文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆