Create your first Go program

Lets write our first hello world program.

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

  # mkdir src
  # tree
  .
  └── src
  
  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:

Create a directory in your workspace:

mkdir -p $GOPATH/src/github.com/<your_user>/hello
cd $GOPATH/src/github.com/<your_user>/hello
touch main.go

Open your favorite editor, and add the following to main.go:

package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

So what have we done here? The package statement indicates the name of the package we are in and the main function is similar to main for other languages. It is the entrypoint of an executable program.

Functions are defined with the func keyword.

We are importing the fmt package from the stdlib and then using it to print to stdout.

Now run:

go build

The go build command will compile the source of the package in the current directory and drop a binary also in the current directory.

./hello

This should output hello world.

Now, try:

rm ./hello
go install
hello

The go install command installs the binary to the $GOPATH/bin directory. If you have added that directory to your PATH, then you can execute the program without the ./.

Finally, open the main.go file and change the formatting to be terrible… Introduce spurious new lines and spaces, then run:

go fmt

Open main.go again and it should be correctly formatted again.

It is highly recommended to configure your editor to run gofmt (or goimports) on save, so that you don’t need to bother about it.

https://github.com/RHCloudServices/golang-intro


See also