Working with Multiple Files in a Go Project

Adler @ 2016-01-23

When developing a Go program, it is inevitable that the codebase becomes too large for a single file. It is better to separate functions and types into different files based on their behaviour in the program. However, there are several things we should follow.

1. Keep the main.go

If you read How to Write Go Code carefully, it states that every go program except library is required to include a main.go file, which serves as the backbone of the program. In this case, no matter how you separate the files, keep the main.go.

2. Consistent package name

Every Go program starts with the line package, and all files in one program shares the same package name, which all files should include the:

package main

at the beginning. Likewise, all package name should be the same if developing a library.

3. Run multiple files at once

When running go run, we usually specify main.go as our target. Nevertheless, if several functions are imported from other files like:

- main.go
- foo.go
- bar.go

We may get undefined error when running go run main.go. This is because go does not load other files automatically. In this case, we run:

go run *.go

The go tool automatically load all files and starts with the main.go.

4. Keep only one main function

Even though files are separated, we run them at once, so there is no need to have multiple main function. Keep that only in main.go.

5. All files in the same directory & no sub-directory

As a Rubist, we separate files into different directories, but it does not work like that in Go. All related files should be put in one directory. If my working directory looks like:

- main.go
- foo
  - foo.go
  - bar.go

And I run:

go run **/*.go

There will be an error message:

named files must all be in one directory; have / and /foo

Thus don't use directories, put them together. This might be not as friendly as other OO project structure like in Ruby where directories are everywhere. However, it is just a way or organizing the codebase. Files become large but there are less files. A good example would be one popular web framework revel which is consisted of many files but all files are ordered and named properly.