Learn Go (Golang) from Scratch

Go Functions, Slices and Maps

Lesson 4 of 7 1 min read Updated 28 September 2026

Functions

func add(a int, b int) int {
    return a + b
}

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

Go functions can return multiple values. Returning (result, error) is the standard pattern.

result, err := divide(10, 2)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(result)

Variadic functions

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

Slices

Slices are flexible lists.

marks := []int{78, 92, 65}
marks = append(marks, 88)
fmt.Println(len(marks), marks[1:3])

copyOf := make([]int, len(marks))
copy(copyOf, marks)

Maps

Maps store key-value pairs.

ages := map[string]int{"Asha": 20, "Ravi": 22}
ages["Meena"] = 21
delete(ages, "Ravi")

age, ok := ages["Asha"]
if ok {
    fmt.Println("Asha is", age)
}
for name, a := range ages {
    fmt.Println(name, a)
}

Closures

func counter() func() int {
    c := 0
    return func() int {
        c++
        return c
    }
}
next := counter()
fmt.Println(next(), next())   // 1 2

Practice

Write a function that takes a slice of numbers and returns the smallest, largest and average values.