Home > Article > Backend Development > How Can I Build a Library and a Standalone Binary with the Same Name in Go?
Multiple Libraries and Binaries with Identical Names
This question explores the possibility of creating a library and a standalone binary with the same name. The example of the Tar command-line tool and its library functionality demonstrates this scenario.
Initially, the user attempted the following directory structure:
src/ tar/ tar.go # belongs to package tar main.go # imports tar and provides a main function
However, this resulted in a "command" called tarbin, not the desired tar command.
To address this, the user employed the workaround of explicitly specifying the output binary name using go build -o $GOPATH/bin/tar tar.
A more elegant solution suggested by the responder is to organize the code as follows:
src/ tar/ tar.go # tar libary tar/ main.go # tar binary
Using this structure, the resulting binary will be named tar, while the library is named tar.
If the code is hosted on GitHub, the directory structure would be as follows:
src/ github.com/ you/ tar/ tar.go # tar libary tar/ main.go # tar binary
This organization ensures that the go command can install both the binary and the library when used with go get install github.com/you/tar/tar.
The advantage of this approach is that it allows for building and testing all the code in the project using go install ./....
The above is the detailed content of How Can I Build a Library and a Standalone Binary with the Same Name in Go?. For more information, please follow other related articles on the PHP Chinese website!