This article covers the four most fundamental steps in learning Go: writing your first program, creating a utility library, writing unit tests, and using remote packages. The content follows the original GOPATH workflow from the early Go 1.x era.
Note: Go Modules were introduced in Go 1.11 and became the default in Go 1.16, effectively replacing GOPATH mode. For new projects, use
go mod initto create a module instead of manually setting up GOPATH. The examples below preserve the original style for reference.
Hello, Go
After installing the Go pkg, configure environment variables. It is recommended to create a go directory under your home folder for development:
| |
Although the documentation does not strictly require these steps, skipping them makes debugging much more painful. Follow Go’s convention to create the directory structure. Create the path info.haoxiqiang/first/hello under $GOPATH/src, then create hello.go:
| |
To run this, you need at least one package named main. There are three ways to execute it:
- Run directly:
go run hello.go - Build and install (omitting the
srcpath):go install info.haoxiqiang/first/hello - Run
go installdirectly in the source directory
A successful run produces no error output, and an executable is generated in $GOPATH/bin. You can run it via cd $GOPATH/bin && ./hello or from anywhere with $GOPATH/bin/hello.
Creating a Library
Real-world projects often use utility classes or third-party libraries. Here is how to create and use a basic Go library:
| |
| |
The package name is what you use when importing. Usage:
| |
Unit Testing
Go includes a lightweight built-in testing framework. Test files should follow the xxx_test.go naming convention:
| |
Run the tests:
| |
This table-driven test pattern is widely adopted in the Go community. By defining a struct slice to cover multiple test cases, it stays concise and easy to extend.
Remote Packages
Go natively supports remote packages. Fetch an official example:
| |
This creates the corresponding directory structure and files under $GOPATH/src. Running $GOPATH/bin/hello displays Hello, Go examples!.
You can also reference remote packages directly in import statements. The go get command handles fetching, building, and installing automatically:
| |
| |
Source code: https://github.com/Haoxiqiang/go-practise