Create Go workspace


Once the Go build environment is ready, the next step is to create workspace for development:

(1) Set up a new empty directory:

  1. # mkdir gowork

(2) Use a new environment variable $GOPATH to point it:

  1. # cat /etc/profile
  2. ......
  3. GOPATH=/root/gowork
  4. export GOPATH
  5. ......

The workspace should contain 3 subdirectories:

src: contains the Go source code.
pkg: contains the package objects. You could think them as libraries which are used in linkage stage to generate the final executable files.
bin: contains the executable files.

Let’s see an example:

(1) Create a src directory in $GOPATH, which is /root/gowork in my system:

  1. # mkdir src
  2. # tree
  3. .
  4. └── src
  5. 1 directory, 0 files

(2) Since Go organizes source code using “package“ concept , and every “package“ should occupy a distinct directory, I create a greet directory in src:

  1. # mkdir src/greet

Then create a new Go source code file (greet.go) in src/greet:

  1. # cat src/greet/greet.go
  2. package greet
  3. import "fmt"
  4. func Greet() {
  5. fmt.Println("Hello 中国!")
  6. }

You can consider this greet directory provides a greet package which can be used by other programs.

(3) Create another package hello which utilizes the greet package:

  1. # mkdir src/hello
  2. # cat src/hello/hello.go
  3. package main
  4. import "greet"
  5. func main() {
  6. greet.Greet()
  7. }

You can see in hello.go, the main function calls Greet function offered by greet package.

(4) Now our $GOPATH layout is like this:

  1. # tree
  2. .
  3. └── src
  4. ├── greet
  5. └── greet.go
  6. └── hello
  7. └── hello.go
  8. 3 directories, 2 files

Let’s compile and install hello package:

  1. # go install hello

Check the $GOPATH layout again:

  1. # tree
  2. .
  3. ├── bin
  4. └── hello
  5. ├── pkg
  6. └── linux_amd64
  7. └── greet.a
  8. └── src
  9. ├── greet
  10. └── greet.go
  11. └── hello
  12. └── hello.go
  13. 6 directories, 4 files

You can see the executable command hello is generated in bin folder. Because hello needs greet package’s help, a greet.a object is also produced in pkg directory, but in system related subdirectory: linux_amd64.

Run hello command:

  1. # ./bin/hello
  2. Hello 中国!

Working as expected!

(5) You should add $GOPATH/bin to $PATH environment variable for facility:

  1. PATH=$PATH:$GOPATH/bin
  2. export PATH

Then you can run hello directly:

  1. # hello
  2. Hello 中国!

Reference:
How to Write Go Code.