BACK TO THE HOMEPAGE

Dec 29, 2020 2 min read

Hello World in Go

The Go programming language is an open source project to make programmers more productive. In the following blog post I assume you already have the Go environment setup. To get started with Go is just a matter of adding some code. The example below covers a basic “Hello World”.

Go Installation

  1. Confirm Go is installed
go version

If it is not installed check out a previous post to install Go in Linux

Development setup

With go already installed, the setup requires a couple more steps

  • Create a directory for your code
  • Initialise the location where the module can be found
  1. Make the go home directory

    mkdir -p ~/hello && cd hello
    
  2. Initialise the hello directory

go mod init example.com/hello
  1. The directory should now look like this:
.
└── go.mod

Hello World

In the hello world example we will perform three things

  • Declare a package name
  • Import the “fmt” package to use the fmt.Println function
  • Declare a main func - which is the entry point for our go application
  1. Create a hello.go program using an editor e.g.

    vi hello.go
    
  2. Add the following code to hello.go

    package main
    import "fmt"
    func main() {
      fmt.Println("hello, world\n")
    }
    
  3. The directory should now look like this:

.
├── go.mod
└── hello.go

Build go

The last thing to do is build our application and run it.

  1. Build the hello.go application

    go build
    
  2. The directory should now look like this:

.
├── go.mod
├── hello
└── hello.go
  1. Run the code hello application
    ./hello
    

The application output should be as per below:

hello, world