Note - How to write go code
- Go programmers typically keep all their Go code in a single workspace.
- A workspace contains many version control repositories (managed by Git, for example).
- Each repository contains one or more packages.
- Each package consists of one or more Go source files in a single directory.
- The path to a package’s directory determines its import path.
Note that this differs from other programming environments in which every project has a separate workspace and workspaces are closely tied to version control repositories.
A workspace is a directory hierarchy with three directories at its root:
- src contains Go source files,
- pkg contains package objects, and
- bin contains executable commands.
The GOPATH environment variable specifies the location of your workspace. It defaults to a directory named go inside your home directory, so $HOME/go on Unix, $home/go on Plan 9, and %USERPROFILE%\go (usually C:\Users\YourName\go) on Windows.
For convenience, add the workspace’s bin subdirectory to your PATH:
$ export PATH=$PATH:$(go env GOPATH)/bin
The scripts in the rest of this document use $GOPATH instead of $(go env GOPATH) for brevity. To make the scripts run as written if you have not set GOPATH, you can substitute $HOME/go in those commands or else run:
$ export GOPATH=$(go env GOPATH)
An import path is a string that uniquely identifies a package. A package’s import path corresponds to its location inside a workspace or in a remote repository (explained below).
The packages from the standard library are given short import paths such as “fmt” and “net/http”. For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries.
go install github.com/user/hello
You can now run the program by typing its full path at the command line:
Or, as you have added $GOPATH/bin to your PATH, just type the binary name:
The first statement in a Go source file must be
Go has a lightweight test framework composed of the go test command and the testing package.
You write a test by creating a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T). The test framework runs each such function; if the function calls a failure function such as t.Error or t.Fail, the test is considered to have failed.
Add a test to the stringutil package by creating the file $GOPATH/src/github.com/user/stringutil/reverse_test.go containing the following Go code.
Then run the test with go test:
$ go test github.com/user/stringutil
As always, if you are running the go tool from the package directory, you can omit the package path:
$ go test
$ go get github.com/golang/example/hello