How to write a simple Go Program

In this tutorial, we are going to look at the basic structure of a Go program and run a simple Hello World program.

How to write a simple Go Program

What is a Go program?

A Go program is just a UTF-8 text file with a .go extension. That means you can write it in a simple text editor, an IDE like VS Code or WebStorm, or even a terminal editor like vim or nano.

💡 If you are using VSCode, then install vscode-go extension. This will help you write better code and make formatting/debugging easier.

Go program structure

Every Go file belongs to a package. If we want to create a standalone executable program, that program must use the main package and define a main function. The main function is where execution starts.

💡 A standalone executable program is a Go program that can be built to an executable using go build command or ran using go run command.

package main

import "fmt"

func main() {
    fmt.Println("Hello World!")
}

In this program, we define package main at the top because this is a standalone executable. We also define the main function, which Go calls when the program starts.

We also imported the fmt package from Go’s standard library (it comes with Go installation). To import a package, we use the import keyword followed by the name of the package in double-quotes.

The fmt package is used here to print messages to the standard output. This package provides different functions to log any data to the standard output (STDOUT) in different formats.

In this example, we use Println, which prints values to the terminal and adds a newline at the end.

Running a Go program

To run a Go program, assuming Go is installed on your system, we use the go run command with the path of the Go file.

If we save the earlier program in hello.go, we can run it from the same directory like this.

$ go run hello.go

This prints the following output.

Hello World!

If the program is split across multiple files, you can pass all of them to go run.

$ go run dir/*.go
$ go run dir/**/*.go
$ go run file-a.go file-b.go file-c.go

This is useful once a program grows and you split different parts of it into separate files.

However, there can be only one main function across those files, because an executable program has only one entry point. The files should also belong to the same directory and package.

If one file depends on a function or variable from another file, that other file must be included in the run or build command.

💡 We will look at this in more detail when we discuss packages.

To create a binary executable file, you can use the go build command.

$ go build hello.go

This creates a hello binary in the current directory, which we can execute from the terminal.

$ ./hello

To install the binary into the Go workspace bin directory, use go install.

$ go install hello.go

This installs the hello binary into the bin directory of the current Go workspace (GOBIN). If that directory is in your system PATH, you can run the binary from anywhere.

$ hello
Hello World!

If you are working with multiple files, the go install *.go or go install file-1.go file-2.go ... command will create a binary file in GOBIN directory with a non-specific filename.

This filename is chosen from the filename of one of the files provided in the command that comes first in alphabetical order. However, this changes when we are compiling a standalone or distributable package. You will learn about this case in the packages lecture.

Comments

Go comments look familiar if you have used languages like JavaScript, Java, or C++. Use // for a single-line comment and /* */ for a block comment.

// I am a single line comment.
// I am another single line comment.
/*
    I am a block comment.
    And GoLang is awesome.
    Say it with me, GoLang is awesome.
*/

Semicolons

You might have noticed that we have not written semicolons so far, even though Go comes from the same family of languages as C.

Go’s formal grammar uses semicolons to terminate statements, but we usually do not write them ourselves. The lexer inserts them automatically while scanning the source code.

The rule is this. If the last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the below tokens

break continue fallthrough return ++ -- ) }

then Lexer always inserts a semicolon after this token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.

So Go code is mostly free of semicolons. If you accidentally write them, the VS Code Go extension or gofmt will usually clean them up for you.

The only place you will find semicolons is where statements have to be terminated deliberately using ; (semicolon) like for,switch, if statements or other variations of them.

You are free to use semicolons whenever you want, but that won’t be idiomatic Go code. For example, you could write the following code and the program will still execute.

package main
import("fmt"; "math";);
func main() {
    fmt.Println(math.Sqrt(16));
};

But the following syntax is the idiomatic way to write Go code.

package main

import(
    "fmt"                           // ;
    "math"                          // ;
)                                   // ;

func main() {
    fmt.Println(math.Sqrt(16))      // ;
}                                   // ;

Best practices

Go is opinionated about formatting, and that is a good thing. gofmt automatically formats Go source code, so most Go projects look consistent even when many people work on them.

Effective Go

Follow the Effective Go documentation to understand these standard practices. https://golang.org/doc/effective_go.html

Go Playground

The Go community provides an online playground for trying small Go programs. Think of it like JSFiddle or CodePen, but for Go.

I would not use the playground for everything. For simple examples it is great, but for concurrency, networking, file I/O, or performance-related experiments, local execution gives you a more realistic result.

#golang #installation