Where To Put Packages

Rather than allowing a package to simply sit next to its importing file. Go imposes a complicated directory layout for packages. The command go help gopath gives a summary. Go looks under two directories given by the environment variables GOROOT and GOPATH. You probably don't want to change GOROOT, since that's where it finds the standard things. You don't want to lose fmt and such. User packages should then go under GOPATH. Source files for a package p must go under a directory given by $GOPATH/src/p. The package is made from one or more .go files located in that directory.

The default GOPATH is /home/userid/go on Linux, for whatever your login id is. (Use go help gopath to see exactly what yours is. Different on Windows, of course.) You can simply create a go directory in your home area, then create a directory src under it, then make directories in src for each of your packages. There are various ways to set GOPATH, temporarily or permanently, if you want to put your sources some other place.

For my example code, I'm using a hack that lets me keep the parts closer together. Say I have a main program for testing called tester.go located in some directory called testdir. The tester.go program says import "testie", which is the name of the package I want to test. I create a directory testie under testdir and place the package files there. (Each is a .go file with a proper package declaration.') Then, from testdir, I run (once) the slightly cryptic Unix command ln -s . src. This essentially makes src an alias for the current directory. I can then build the program with the command

GOPATH=$PWD go build tester.go