I have a project that provides a library (exports some funcs) and also must provide a command-line interface (there must be an executable file).
Example of directory structure:
whatever.io/
myproject/
main.go
myproject.go
The go compiler needs the package main and func main to start execution. My library needs the package myproject where I put stuff on it. This is what the go tool says when I am building another project that tries to import myproject:
main.go:5:2: found packages myproject (myproject.go) and main (main.go) in $GOPATH/src/whatever.io/myproject
So I believe there is no way to do it.
Should I move the library or the CLI to another package?
Just move your packages inside a new folder within the same directory of main.go. Remember to import the new package from the reference of the $GOPATH.
Example:
Useful link:
go build vs go build file.go
In most cases, no. However, there is an exception for unit tests.
Working Example:
Here are 2 different packages (
mypackage
andmypackage_test
) in 1 directory (mypackage
). The compiler will not complain about this.mypackage folder:
mypackage/foo.go:
mypackage/foo_test.go:
Rules:
The 2 packages must have the following names:
_test
.The names of the files in the
_test
package must end with_test.go
If you're receiving a confusing compiler error along the lines of
found packages "foo" and "bar"
, you've probably broken one or more of these rules.You cannot have two packages per directory, hence the error. So the solution as @Larry Battle said to move your
myproject.go
to a new directory.From How to write go code