Does it make sense to have two packages in the same directory?
Solution 1:
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:
user@user:~/p/go/test/so-multipack$ ls -R
.:
a main.go
./a:
a.go
user@user:~/p/go/test/so-multipack$ cat main.go
package main
import (
"../so-multipack/a"
)
func main(){
a.Hello()
}
user@user:~/p/go/test/so-multipack$ cat a/a.go
package a
import (
"fmt"
)
func Hello(){
fmt.Println("hello from a")
}
user@user:~/p/go/test/so-multipack$ go run main.go
hello from a
user@user:~/p/go/test/so-multipack$ go build
user@user:~/p/go/test/so-multipack$ ls
a main.go so-multipack
user@user:~/p/go/test/so-multipack$
Useful link:
go build vs go build file.go
Solution 2:
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
Go code must be kept inside a workspace. A workspace is a directory hierarchy with three directories at its root:
src contains Go source files organized into packages (one package per directory),
pkg contains package objects, and
bin contains executable commands.
Solution 3:
In most cases, no. However, there is an exception for unit tests.
Working Example:
Here are 2 different packages (mypackage
and mypackage_test
) in 1 directory (mypackage
). The compiler will not complain about this.
mypackage folder:
mypackage/
foo.go
foo_test.go
mypackage/foo.go:
package mypackage
func Add(a int, b int) int {
return a + b
}
mypackage/foo_test.go:
package mypackage_test
// Unit tests...
Rules:
-
The 2 packages must have the following names:
- NameOfDirectory.
- NameOfDirectory +
_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.