Recursive compilation files
I just started with Go and I love it! I tried to make my project structure a little more manageable, instead of having everything in my main.go
So now I have a structure like this.
src/
-> main.go
-> routes.go
-> handlers/
--> user_handlers.go
But when I try to build this with the following command
go build -v -o ./bin/my_bin ./src/...
I am getting this error
cannot use -o with multiple packages
But if I create a flat structure like this
src/
-> main.go
-> routes.go
-> user_handlers.go
It works fine, all my files got the "main package" at the top.
What am I doing wrong?
source to share
The package name must match the directory name. To move the source file to a new directory, you must also change the package name.
foo/foo.go // package foo
foo/bar/bar.go // package bar
foo/bar/qux.go // package bar
PATH has nothing to do with the package name.
Package foo: /some/path/some/where/foo
This allows you to create and import multiple "foo" packages as long as your import specifies the desired "foo" location
PS The package naming convention has lowercase values, no punctuation (e.g. no _)
source to share
It tells you what you did wrong, you cannot separate one package from multiple folders.
You need to install and use $GOPATH
correctly and import the folder correctly routes/
into routes.go
.
A simple example of this is:
// routes.go
// the . means you can call imported functions without prefixing them with the package name
import . "full-path-to-routes/-relative-to-$GOPATH"
From https://golang.org/doc/code.html :
The GOPATH environment variable indicates the location of your workspace. This is most likely the only environment variable you need to set when developing your Go code.
To get started, create a workspace directory and set GOPATH accordingly. Your workspace can be located wherever you like, but we'll use $ HOME / go throughout this document. Please note that this does not have to be the same path as your Go installation.
I highly recommend reading Effective Option .
source to share