Go operates on packages (usually one folder is one package) and all files in one package are in the same scope. It is as if all the code from all files in a single folder would be running in the same file. So every function, variable, type and so on needs to have a unique name in your package.
If you want to create one big folder with all your test examples in them (for example like me, I like to have one GitHub repo with all my test files in it), the best solution is to create multiple subdirectories within that folder. In each subdirectory, you can place you example code, but you leave the top level folder empty.
For example:
– Top level of repository –> do not place your .go files in here
–- example1 –> place one .go file here
– example 2 –> place one .go file here
– etc….
In this example, the only reason for having multiple .go files in one subdirectory is if they have a different package. So for example in your package main you also use a second package (sort of a library), to keep the main package clean.
Barring some exceptions like _test packages, multiple files in the same directory will be the same package. If you want to have a bunch of examples in subfolders, I often create a go module in the parent folder and then run them with relative paths. I wrote about this recently on another question here.
In each directory, the program’s Go files declare package main. A top-level internal directory can contain shared packages used by all commands in the repository.
Users can install these programs as follows:
$ go install github.com/someuser/modname/prog1@latest
$ go install github.com/someuser/modname/prog2@latest
# Clone that repo (note how many subfolders it has)
git clone https://github.com/adonovan/gopl.io.git
# Switch to newly-cloned folder
cd gopl.io
# Run one of the examples using relative path
go run ./ch1/helloworld
# Can also run with module name in go.mod:
go run gopl.io/ch1/helloworld