Home >Backend Development >Golang >Can I Bundle a Go Library and CLI in the Same Directory?
Can You Bundle Library and CLI in the Same Directory?
Having a directory with separate packages for a library (exported functions) and a command-line interface (CLI executable) raises the question of whether it's practical. The issue arises when the go compiler requires both a package with a "main" function for program execution and the library with its functions.
The Problem: Multiple Packages
As the provided example illustrates, if both "main" and the library package coexist in the same directory, the go compiler complains about finding multiple packages in the same directory.
The Solution: Nested Packages
Instead of maintaining the packages in the same directory, a simple solution is to create a new subdirectory within the parent directory to house either the library or the CLI package. Remember to update your imports to reflect the new location of the package.
Example with Nested Packages
In the revised example below, the "a" package is moved into a new subdirectory "a" within the "so-multipack" directory:
so-multipack/ a/ a.go main.go
Updated main.go
package main import "../so-multipack/a" func main() { a.Hello() }
Updated a/a.go
package a import "fmt" func Hello() { fmt.Println("hello from a") }
Successful Compilation
Using the updated directory structure, the go commands now run successfully:
go run main.go # Output: hello from a go build # Creates a "so-multipack" executable
By nesting the packages within the same parent directory, we can successfully accommodate both the library and the CLI executable.
The above is the detailed content of Can I Bundle a Go Library and CLI in the Same Directory?. For more information, please follow other related articles on the PHP Chinese website!