Managing Shared Names in Libraries and Binaries
When developing software, it may be desirable to have both a library and a standalone executable with the same name. This can lead to challenges in Go, as the recommended approach is for executables and libraries to have distinct names.
In the example provided, the developer is attempting to create a library for Tar operations, but also wants a standalone Tar command-line utility. The initial approach of placing the executable code in a directory named main.go within the library package doesn't work as expected.
To resolve this, it's recommended to organize the codebase as follows:
src/ tar/ tar.go # tar library tar/ main.go # tar binary
With this structure, go build -o $GOPATH/bin/tar tarbin constructs both a library named tar and a binary named tar.
If the code is hosted on GitHub, the preferred directory structure becomes:
src/ github.com/ you/ tar/ tar.go # tar library tar/ main.go # tar binary
This layout ensures that when running go get install github.com/you/tar/tar, a binary named tar is installed, and go get install github.com/you/tar installs the library named github.com/you/tar.
Depending on the primary purpose of the codebase, the library and binary can be swapped in the directory structure.
By using separate subdirectories for the library and binary within the package directory, developers can effectively manage code with shared names in Go, enabling both library and standalone executable functionality.
The above is the detailed content of How Can I Build Both a Go Library and a Standalone Executable with the Same Name?. For more information, please follow other related articles on the PHP Chinese website!