Brainbotox · Lessons · Exams

Go (Golang) Fundamentals for Beginners: Syntax, Slices, Structs

by lazizanie · Programming · Go · English

Learn Go from zero: the go toolchain, variables and types, control flow, functions and pointers, slices and maps, structs, methods and errors, with quizzes.

Study this lesson with its quizzes on Brainbotox →

What is Go? The toolchain and your first program

Go (also called Golang) is a statically typed, compiled, garbage-collected language created at Google, designed for simple, fast and concurrent server software. One command, go, builds, runs, tests and formats your code.

Your first program

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

Every executable starts in package main, in the function main. Code is organised in packages, and import brings in other packages such as fmt from the standard library.

The go command

CommandWhat it does
go run main.goCompiles and runs in one step
go buildProduces a single native executable
go mod init example.com/helloCreates a module, described by go.mod
go testRuns the tests
go fmtFormats code in the one standard style
go vetReports suspicious code
Go compiles to one static binary. No virtual machine or runtime needs to be installed on the server: the scheduler and garbage collector are embedded in the executable.

Rules that surprise newcomers

  • An unused import or unused local variable is a compile error.
  • A name that starts with a capital letter is exported (visible from other packages). A lowercase name is private to its package.
  • The opening brace must be on the same line as the statement.
  • There are no classes, no inheritance and no exceptions. Go uses structs, interfaces and error values.

Check yourself

  1. Which package and function does a Go executable start in?
  2. What happens when a Go file imports a package it does not use?
  3. How do you make a Go function visible to other packages?
  4. Which command creates a new Go module?
  5. A compiled Go program needs a separate virtual machine installed to run.
  6. Which tool gives all Go code the same formatting?

Take the quiz on Brainbotox

Go variables, types, constants and zero values

Every Go variable has a fixed type known at compile time, and a variable declared without a value is automatically set to the zero value of its type.

Declaring variables

var name string = "Ada"
var age = 36          // type inferred: int
count := 10           // short declaration, only inside functions
var ready bool        // zero value: false

Zero values

TypeZero value
Numbers (int, float64)0
string"" (empty string)
boolfalse
Pointers, slices, maps, channels, functions, interfacesnil

Basic types

int, int8 to int64, uint variants, float32, float64, bool, string, byte (alias of uint8) and rune (alias of int32, one Unicode code point).

Constants

const Pi = 3.14159
const (
    Low = iota   // 0
    Medium       // 1
    High         // 2
)

Conversions are always explicit

i := 7
f := float64(i) / 2   // 3.5
n := i / 2            // 3: integer division
// var x float64 = i  // compile error: no implicit conversion
Go never converts between numeric types automatically, not even int to int64.

Strings

A string is an immutable sequence of bytes, normally UTF-8 text. len(s) counts bytes, not characters, and a for range loop over a string yields runes.

s := "héllo"
fmt.Println(len(s))            // 6 bytes
fmt.Println(len([]rune(s)))    // 5 characters

Check yourself

  1. What is the zero value of a string variable in Go?
  2. Where can the short declaration := be used?
  3. Given i := 7 (an int), what does var f float64 = i do?
  4. What does len(s) return for a Go string?
  5. What is a rune in Go?
  6. In a const block, what does iota do?

Take the quiz on Brainbotox

Go control flow: if, for, switch and defer

Go has one loop keyword, for, plus if, switch and defer. Conditions take no parentheses, and braces are always required.

if with an init statement

if n, err := strconv.Atoi(text); err != nil {
    fmt.Println("not a number")
} else if n > 100 {
    fmt.Println("big")
}

The variables declared before the semicolon exist only inside the if and its else branches.

The three forms of for

for i := 0; i < 3; i++ { }      // classic
for n < 100 { n *= 2 }          // like while
for { break }                   // infinite loop
for i, v := range []string{"a", "b"} {
    fmt.Println(i, v)           // index and value
}

Use _ to ignore the index: for _, v := range items. break leaves the loop and continue goes to the next iteration.

switch

switch day {
case "Sat", "Sun":
    fmt.Println("weekend")
default:
    fmt.Println("weekday")
}
switch {                        // no value: a clean if/else chain
case score >= 90:
    grade = "A"
case score >= 70:
    grade = "B"
}
A Go case does not fall through to the next one. No break is needed. Write fallthrough explicitly if you want it.

defer

f, err := os.Open("data.txt")
if err != nil { return err }
defer f.Close()     // runs when the surrounding function returns

Deferred calls run when the function returns, in last in, first out order. They are the usual way to close files and unlock mutexes.

Check yourself

  1. How many loop keywords does Go have?
  2. In Go, a switch case falls through to the next case unless you write break.
  3. When does a deferred call run?
  4. Three calls are deferred in the order A, B, C. In which order do they run?
  5. What does for i, v := range items give you?
  6. In if x := f(); x > 0 { }, where is x visible?

Take the quiz on Brainbotox

Go functions, multiple return values and pointers

A Go function can return several values, and every argument is passed by value, meaning the function receives a copy. To let a function change the caller's data, pass a pointer.

Declaring functions

func add(a, b int) int {
    return a + b
}
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
result, err := divide(10, 2)

Returning a value together with an error is the standard Go pattern.

Variadic functions

func sum(nums ...int) int {
    total := 0
    for _, n := range nums { total += n }
    return total
}
sum(1, 2, 3)

Functions are values

double := func(x int) int { return x * 2 }
func counter() func() int {
    n := 0
    return func() int { n++; return n }   // closure: remembers n
}

Pointers

func reset(p *int) { *p = 0 }
x := 5
reset(&x)        // &x is the address of x
fmt.Println(x)   // 0
SyntaxMeaning
*intThe type "pointer to int"
&xThe address of x
*pThe value p points to
Without a pointer, a function works on a copy and the caller's variable is unchanged.
The zero value of a pointer is nil. Dereferencing a nil pointer causes a run-time panic. Go has no pointer arithmetic.

Check yourself

  1. How are arguments passed to Go functions?
  2. What is the idiomatic way for a Go function to report failure?
  3. What does &x mean?
  4. What happens when you dereference a nil pointer?
  5. In func sum(nums ...int), what is the type of nums inside the function?
  6. A Go closure can read and modify variables of the function that created it.

Take the quiz on Brainbotox

Go arrays, slices and maps

A slice is a resizable view over an array and is the list type you use every day in Go, while a map stores key to value pairs. Arrays have a fixed size and are rarely used directly.

Arrays

var a [3]int            // [0 0 0]
b := a                  // copies the whole array

The size is part of the type: [3]int and [4]int are different types.

Slices

s := []int{1, 2, 3}
s = append(s, 4)            // append returns the new slice: assign it
fmt.Println(len(s), cap(s)) // length and capacity
buf := make([]int, 0, 10)   // length 0, capacity 10
part := s[1:3]              // elements 1 and 2
Slicing does not copy. part shares the same underlying array as s, so part[0] = 99 also changes s[1]. Use copy or slices.Clone for an independent slice.
Always write s = append(s, x). When capacity runs out, append allocates a bigger array and returns a slice that points to it.

Maps

ages := map[string]int{"Ada": 36}
ages["Bob"] = 41
age, ok := ages["Eve"]   // 0, false: the "comma ok" form
delete(ages, "Bob")
for name, age := range ages {
    fmt.Println(name, age)
}
  • Reading a missing key returns the zero value, with no error. Use the ok result to tell "missing" from "zero".
  • The iteration order of a map is not defined and changes between runs.
  • Writing to a nil map panics. Create maps with make or a literal.

Check yourself

  1. What is the correct way to add an element to a slice s?
  2. After part := s[1:3], what happens when you set part[0] = 99?
  3. What does reading a missing key from a Go map return?
  4. What happens when you write to a nil map?
  5. Iterating over a Go map always visits keys in insertion order.
  6. What is true of Go arrays?

Take the quiz on Brainbotox

Go structs, methods and error handling

Go has no classes: you group data in a struct, attach behaviour with methods, and report problems by returning error values.

Structs

type User struct {
    Name string
    Age  int
}
u := User{Name: "Ada", Age: 36}
u.Age++
p := &u
p.Age++          // Go dereferences automatically

Methods and receivers

func (u User) Greeting() string {     // value receiver: works on a copy
    return "Hi, " + u.Name
}
func (u *User) Birthday() {           // pointer receiver: can modify
    u.Age++
}
Use a pointer receiver when the method must change the struct or the struct is large. A value receiver gets a copy, so its changes are lost.

Composition by embedding

type Admin struct {
    User              // embedded: Admin gets Name, Age and User's methods
    Level int
}
a := Admin{User: User{Name: "Bob"}, Level: 2}
fmt.Println(a.Name)

Go favours composition. There is no inheritance.

Errors are values

data, err := os.ReadFile("config.json")
if err != nil {
    return fmt.Errorf("reading config: %w", err)   // add context
}

error is a built-in interface with one method, Error() string. Create errors with errors.New("...") or fmt.Errorf. A nil error means success.

Do not ignore errors with _. Handle each one or return it to the caller.

panic

panic stops normal execution and is reserved for bugs and unrecoverable situations, such as an index out of range. Ordinary failures (file missing, bad input) are returned as errors.

Check yourself

  1. Which receiver lets a method modify the struct it is called on?
  2. How does Go reuse the fields and methods of one struct in another?
  3. What does a nil error mean?
  4. What is the error type in Go?
  5. When is panic appropriate?
  6. Go supports class inheritance.

Take the quiz on Brainbotox