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
- Confirm Go is installed
NODE_TYPE // bash
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
-
Make the go home directory
NODE_TYPE // bashmkdir -p ~/hello && cd hello -
Initialise the hello directory
NODE_TYPE // bashgo mod init example.com/hello -
The directory should now look like this:
NODE_TYPE // text. └── 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
-
Create a hello.go program using an editor e.g.
NODE_TYPE // bashvi hello.go -
Add the following code to hello.go
NODE_TYPE // gopackage main import "fmt" func main() { fmt.Println("hello, world\n") } -
The directory should now look like this:
NODE_TYPE // bash. ├── go.mod └── hello.go
Build go
The last thing to do is build our application and run it.
-
Build the hello.go application
NODE_TYPE // bashgo build -
The directory should now look like this:
NODE_TYPE // bash. ├── go.mod ├── hello └── hello.go -
Run the code hello application
NODE_TYPE // bash./hello -
The application output should be as per below:
NODE_TYPE // bashhello, world