Go is a fast and simple programming language. Its code is tidy and easy to read, so it is a good first language. This tutorial covers the basics: install, variables, branching, loops, functions, and input/output.

Install Go

On Arch Linux, install Go with pacman. The command is one line:

sudo pacman -S go

On other operating systems, download the installer from go.dev. Pick the latest stable version, then follow the install steps.

Check the installed version with this command:

go version

The result should look like go1.22.2 linux/amd64 (the numbers may differ). If you see a “command not found” error, Go is not installed yet.

Hello world

Every Go program needs two things. First, the line package main at the very top. Second, the function func main() as the program’s starting point. Without both, the program cannot run.

Create a file named main.go with this code:

package main

import "fmt"

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

import “fmt” loads the fmt package (short for format). This package holds the commands for printing text to the screen. A package must be imported before use, or the program fails to build.

Run it with this command:

go run main.go

The result: Hello, world! is printed in the terminal.

Note: go run only runs the program, without saving a finished file. To build a file you can run directly, use go build. That command creates a file named main in the same folder.

Second note: the opening brace ({) must stay on the same line as func main(), if, or for. Never move it to its own line, or Go reports an error. This is a fixed Go rule, not a style choice.

Flow: main.go, go run, output

Go program structure: package main, import fmt, func main

Variables

A variable is a labeled box for storing a value. Go has two ways to create one. First, the keyword var with the type written out:

var name string = "Briyan"
var age int = 25

Second, the := sign (short declaration). Go guesses the type from the value:

name := "Briyan"
age := 25

Variable names may hold letters, numbers, and underscores. They cannot start with a number, and they cannot hold spaces. Names are case sensitive: name and Name are two different variables.

Note: a variable that is created but never used makes the program fail. Go rejects code with unused variables. Delete the variable, or use it in the code.

Basic data types

Every value has a type (kind of data). These four basic types are used most:

  • string: text, written between quotes. Example: “Briyan”.
  • int (integer): whole numbers. Example: 25.
  • float64: decimal numbers, with a dot, not a comma. Example: 19.5.
  • bool (boolean): only true or false. All letters are lowercase.
name := "Briyan"   // string
age := 25          // int
price := 19.5      // float64
passed := true     // bool

Go guesses that 19.5 is a float64 (a 64-bit decimal). This is the most common decimal type in Go. For math with numbers from the user, use float64 so division can give a decimal result.

if / else

if runs code only when its condition is true. else runs other code when the condition is false. This is called branching.

age := 20

if age >= 18 {
	fmt.Println("You may enter")
} else {
	fmt.Println("Not yet")
}

Comparison operators used most often: == (equal to), != (not equal to), > (greater than), < (less than), >= and <=.

Note: to compare, use == (two equals signs). One equals sign (=) means storing a value, not comparing. Mix them up, and the condition is always true.

Second note: else must stay on the same line as the closing brace (}) of the if. This is the same brace rule as above. Write } else { on one line.

for loop

Go has only one loop keyword: for. There is no while in Go. A for loop has three parts: start, condition, and step.

for i := 1; i <= 5; i++ {
	fmt.Println("Count:", i)
}

The result:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Read it like this: start from i := 1, repeat while i <= 5, and run i++ (add 1) after each round. The sign ++ means add one.

for can also work like while, by writing only the condition:

number := 1

for number <= 3 {
	fmt.Println(number)
	number++
}

Warning: make sure the condition can become false. If not, the loop runs forever (an infinite loop) and the program hangs. Press Ctrl+C in the terminal to stop it.

for loop flow: start, check condition, print, add one

Functions

A function is a named block of code you can call again and again. Write it once, use it anywhere. Create a function with the keyword func, then a name and parentheses. A function can take input (parameters) and give back a result (return).

func greet(name string) string {
	return "Hello, " + name + "!"
}

func main() {
	fmt.Println(greet("Briyan")) // Hello, Briyan!
	fmt.Println(greet("Kirana")) // Hello, Kirana!
}

The parameter type comes after its name, like name string. The result type comes after the parentheses, like the string after (name string). A function with no result needs no result type.

Call a function by writing its name, then parentheses. Put the values to send inside the parentheses. Forgetting the parentheses means the function never runs, it is only named.

Common mistakes

  • Forgetting package main or func main(), so the program cannot run.
  • Writing the opening brace on its own line, so the program fails.
  • Using fmt without import “fmt” at the top.
  • Comparing with =, when it should be ==.
  • Creating a variable but never using it, so the program fails.
  • Dividing whole numbers (int) and being surprised the result is whole too. Example: 10 / 4 gives 2, not 2.5.

If you get stuck, ask Muse (yue) to explain the line that failed. Paste the error message from the terminal so the answer is exact.

Complete example: mini CLI calculator

Put it all together in one program. This program asks the user for two numbers, then shows the add, subtract, multiply, and divide results.

Copy the code below into a file named main.go, then run it with go run main.go.

package main

import "fmt"

func main() {
	var a, b float64

	fmt.Print("First number: ")
	fmt.Scan(&a)
	fmt.Print("Second number: ")
	fmt.Scan(&b)

	fmt.Println("Add:", a+b)
	fmt.Println("Subtract:", a-b)
	fmt.Println("Multiply:", a*b)
	fmt.Println("Divide:", a/b)
}

Example run, with the numbers 10 and 4:

First number: 10
Second number: 4
Add: 14
Subtract: 6
Multiply: 40
Divide: 2.5

How it works: fmt.Scan(&a) reads a number from the user and stores it in the variable a. The & sign means the address of the variable, and it is required so Scan can fill in the value. The operators +, -, *, and / compute the four operations. The numbers are stored as float64 so division gives a decimal, so 10 / 4 is 2.5.

Note: never divide by zero. Dividing a float64 by zero is not an error, but the result is +Inf (infinity), not a number.