Home >Backend Development >Golang >How Can I Build a Go Library and Binary with the Same Name?
Library and Binary with Same Name
A common challenge arises when designing a library that can also function as a standalone binary. While it seems logical to name the library and binary identically, the Golang build system often assigns different names.
One solution involves separating the directory structure into a tar directory for the library and a tarbin directory for the binary. However, this approach creates a binary called tarbin instead of tar.
A more elegant solution is to nest the binary within the library directory:
src/ tar/ tar.go # tar library tar/ main.go # tar binary
This structure produces a binary named tar and a library named tar.
In a GitHub context, the directory structure becomes:
src/ github.com/ you/ tar/ tar.go # tar library tar/ main.go # tar binary
This structure allows for easy installation of both the binary (go get install github.com/you/tar/tar) and the library (go get install github.com/you/tar).
Depending on the desired prominence, the library and binary can be swapped within the directory structure. Additionally, keeping all code in a single tree enables convenient building and testing:
go install ./... go test|fmt ./...
The above is the detailed content of How Can I Build a Go Library and Binary with the Same Name?. For more information, please follow other related articles on the PHP Chinese website!