Go (Golang) Fundamentals for Beginners: Syntax, Slices, Structs
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
| Command | What it does |
|---|---|
go run main.go | Compiles and runs in one step |
go build | Produces a single native executable |
go mod init example.com/hello | Creates a module, described by go.mod |
go test | Runs the tests |
go fmt | Formats code in the one standard style |
go vet | Reports suspicious code |
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
- Which package and function does a Go executable start in?
- What happens when a Go file imports a package it does not use?
- How do you make a Go function visible to other packages?
- Which command creates a new Go module?
- A compiled Go program needs a separate virtual machine installed to run.
- Which tool gives all Go code the same formatting?
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
| Type | Zero value |
|---|---|
Numbers (int, float64) | 0 |
string | "" (empty string) |
bool | false |
| Pointers, slices, maps, channels, functions, interfaces | nil |
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
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
- What is the zero value of a string variable in Go?
- Where can the short declaration := be used?
- Given i := 7 (an int), what does var f float64 = i do?
- What does len(s) return for a Go string?
- What is a rune in Go?
- In a const block, what does iota do?
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"
}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 returnsDeferred 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
- How many loop keywords does Go have?
- In Go, a switch case falls through to the next case unless you write break.
- When does a deferred call run?
- Three calls are deferred in the order A, B, C. In which order do they run?
- What does for i, v := range items give you?
- In if x := f(); x > 0 { }, where is x visible?
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| Syntax | Meaning |
|---|---|
*int | The type "pointer to int" |
&x | The address of x |
*p | The value p points to |
nil. Dereferencing a nil pointer causes a run-time panic. Go has no pointer arithmetic.Check yourself
- How are arguments passed to Go functions?
- What is the idiomatic way for a Go function to report failure?
- What does &x mean?
- What happens when you dereference a nil pointer?
- In func sum(nums ...int), what is the type of nums inside the function?
- A Go closure can read and modify variables of the function that created it.
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 2part shares the same underlying array as s, so part[0] = 99 also changes s[1]. Use copy or slices.Clone for an independent slice.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
okresult to tell "missing" from "zero". - The iteration order of a map is not defined and changes between runs.
- Writing to a
nilmap panics. Create maps withmakeor a literal.
Check yourself
- What is the correct way to add an element to a slice s?
- After part := s[1:3], what happens when you set part[0] = 99?
- What does reading a missing key from a Go map return?
- What happens when you write to a nil map?
- Iterating over a Go map always visits keys in insertion order.
- What is true of Go arrays?
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 automaticallyMethods 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++
}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.
_. 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
- Which receiver lets a method modify the struct it is called on?
- How does Go reuse the fields and methods of one struct in another?
- What does a nil error mean?
- What is the error type in Go?
- When is panic appropriate?
- Go supports class inheritance.