← Back to course

Free trial: Golang Developer

Complete a couple of real lessons from this course — no signup required.

01

Lesson 1: Packages, comments, variables & operators

Packages. Comments.

Any Go code lives inside a package. A package is a folder that contains .go files.

Let's look at the first simple example of a Go program:

main.go
package main

import "fmt"

func main() {
    fmt.Println("Salem Bitlab!")
}
Output:Salem Bitlab!
GOLANG
Output

To run this program we used the main and fmt packages.

package main is the main package. It must contain a func main() function, which is the program's entry point. When you run a Go application, this is exactly the function that gets called first.

package fmt is a standard package used for printing data to the console. Besides printing, it also supports formatted input and output.

As a program grows, its code becomes harder to read and understand. Comments are used to make the program's logic easier to follow.

Comments explain code and split it up logically. They don't take part in compilation and have no effect on how the program runs.

Types of comments

Single-line comments

main.go
package main

import "fmt"

func main() {
    fmt.Println("I like Bitlab Academy!") // prints text to the console
}
Output:I like Bitlab Academy!
GOLANG
Output

A single-line comment is used for a brief note about a specific line or part of the code.

Multi-line comments

main.go
package main

import "fmt"

/*
    In this program,
    using the "fmt" package,
    we print data
    to the console
*/
func main() {
    fmt.Println("I like Bitlab Academy!")
}
Output:I like Bitlab Academy!
GOLANG
Output

Multi-line comments are used for a detailed description of functions, structs, and larger logical blocks of code.

Variables and data types

Go is a statically typed programming language. The Go compiler checks data types before the program runs, which gives it high reliability, performance, and readability.

Go is such a fast language that I call it the Flash of the programming world.

— Suslikov Bitlabkhan, a figure publicly recognized for his contribution to acquiring useful skills

Before getting into data types, it's worth understanding what a variable actually is.

A variable is a piece of memory that holds a value. Every variable has a data type, which determines what operations can be performed on it.

Declaring a variable looks like this:

main.go
package main

import "fmt"

func main() {
    var age int = 22
    fmt.Println(age)
}
Output:22
GOLANG
Output

To declare a variable, we use the var keyword, then the variable name and its data type. After that we can freely use the variable in the program.

Go also has a short form for declaring a variable:

main.go
package main

import "fmt"

func main() {
    age := 22
    fmt.Println(age)
}
Output:22
GOLANG
Output

Using the := operator, Go automatically infers the variable's type from the value being assigned.

Main data types in Go

For working with numbers:

  • int — positive and negative whole numbers
  • uint — positive whole numbers only
  • float32 — decimal numbers (32-bit)
  • float64 — decimal numbers (64-bit)
  • complex64 — complex numbers (2 × float32)
  • complex128 — complex numbers (2 × float64)

For working with strings:

  • string — text data

For boolean logic:

  • bool — true or false

For working with collections of data:

  • array — a fixed-length array
  • slice — a dynamic-length array
  • map — a key-value structure
  • struct — a group of different data types
  • interface — an abstract data type

Additional data types:

  • pointer — a pointer
  • function — a function as a data type
  • channel — communication between goroutines

Math operators

Math operators let you perform operations on numbers.

Addition (+)

a := 2
b := 2
c := a + b // 4
GOLANG
Output

Subtraction (-)

a := 10
b := 5
c := a - b // 5
GOLANG
Output

Multiplication (*)

a := 3
b := 3
c := a * b // 9
GOLANG
Output

Division (/)

a := 6
b := 2
c := a / b // 3
GOLANG
Output

Remainder (%)

a := 7
b := 3
c := a % b // 1
GOLANG
Output

Increment (++)

a := 7
a++ // 8
GOLANG
Output

Decrement (--)

a := 7
a-- // 6
GOLANG
Output

That's enough material for now — it's recommended to practice by solving a few exercises. Good luck!

02

Lesson 2: Conditionals & Logical Operators

What are conditions in Go?

In real programs, code doesn't always run top to bottom in the same way. Sometimes the program has to make a decision: run one block of code, or another.

For example:

  • if the user's age is 18 or older — allow access;
  • if the password is correct — log in;
  • if the balance is enough — process the payment;
  • if the score is high — print a success message.

Go uses conditional statements for situations like these. They let the program choose which code to run.

A condition is an expression whose result is always true or false.

How does a condition work?

A conditional statement checks an expression. If the result is true, one block of code runs. If the result is false, that block is skipped, or a different block runs instead.

The if statement

The simplest conditional statement is if. It only runs its code when the condition is true.

main.go
package main

import "fmt"

func main() {
    age := 20

    if age >= 18 {
        fmt.Println("Access granted")
    }
}
Output:Доступ разрешён
GOLANG
Output

Here the program checks the condition age >= 18. The variable age equals 20, so the condition is true, which means the code inside the if block runs.

Important: in Go, the condition inside if isn't wrapped in parentheses. But the curly braces { } are required.

The if ... else statement

When you need to run one piece of code if a condition is true, and a different piece if it's false, you use if ... else.

main.go
package main

import "fmt"

func main() {
    age := 15

    if age >= 18 {
        fmt.Println("Access granted")
    } else {
        fmt.Println("Access denied")
    }
}
Output:Доступ запрещён
GOLANG
Output

age equals 15. The condition age >= 18 returns false. So the if block is skipped, and the else block runs instead.

Multiple conditions: else if

Sometimes two options aren't enough. For example, you might need to check a student's score and print a different result for each range. That's what else if is for.

main.go
package main

import "fmt"

func main() {
    score := 85

    if score >= 90 {
        fmt.Println("Excellent")
    } else if score >= 75 {
        fmt.Println("Good")
    } else if score >= 50 {
        fmt.Println("Could be better")
    } else {
        fmt.Println("Failed")
    }
}
Output:Хорошо
GOLANG
Output

The program checks the conditions top to bottom:

score >= 90 — false
score >= 75 — true
"Хорошо" is printed
the remaining conditions are never checked

Comparison operators

Comparison operators are commonly used to build conditions. They compare values and return either true or false.

  • == — equal to
  • != — not equal to
  • > — greater than
  • < — less than
  • >= — greater than or equal to
  • <= — less than or equal to
main.go
package main

import "fmt"

func main() {
    a := 10
    b := 5

    fmt.Println(a == b)
    fmt.Println(a != b)
    fmt.Println(a > b)
    fmt.Println(a < b)
}
Output:false true true false
GOLANG
Output

Logical operators

Logical operators let you combine several conditions. That's useful when a single comparison isn't enough.

  • && — AND, both conditions must be true
  • || — OR, at least one condition must be true
  • ! — NOT, flips true to false and false to true

When you need to check several rules at once, && and || are the ones you'll reach for most often.

Example with &&

The && operator means both conditions must be true. For example, a user can only log in if both the login and password are correct.

main.go
package main

import "fmt"

func main() {
    login := "admin"
    password := "12345"

    if login == "admin" && password == "12345" {
        fmt.Println("Welcome")
    } else {
        fmt.Println("Invalid login or password")
    }
}
Output:Добро пожаловать
GOLANG
Output

Example with ||

The || operator means it's enough for just one condition to be true. For example, a city might be called Astana or Nur-Sultan.

main.go
package main

import "fmt"

func main() {
    city := "Astana"

    if city == "Astana" || city == "Nur-Sultan" {
        fmt.Println("Hello, capital")
    } else {
        fmt.Println("That's a different city")
    }
}
Output:Здравствуй столица
GOLANG
Output

Example with !

The ! operator flips a boolean expression to its opposite. If it was true, it becomes false. If it was false, it becomes true.

main.go
package main

import "fmt"

func main() {
    isBlocked := false

    if !isBlocked {
        fmt.Println("User is active")
    } else {
        fmt.Println("User is blocked")
    }
}
Output:Пользователь активен
GOLANG
Output

Initializing a variable inside if

Go lets you create a variable right inside an if statement. That variable is only available within that condition.

main.go
package main

import "fmt"

func main() {
    if age := 19; age >= 18 {
        fmt.Println("Adult")
    } else {
        fmt.Println("Minor")
    }
}
Output:Совершеннолетний
GOLANG
Output

The age variable is created right before the condition is checked. Once the if ... else statement ends, that variable can no longer be used.

The switch ... case statement

When you need to compare one value against several options, switch ... case is a clean way to do it.

It makes the code cleaner when there are a lot of options.

main.go
package main

import "fmt"

func main() {
    day := 3

    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    default:
        fmt.Println("Weekend or unknown day")
    }
}
Output:Среда
GOLANG
Output

In Go, you don't need to write break after each case. Once a matching case runs, the switch statement ends automatically.

default runs when none of the cases matched.

switch without a value

Go also lets you use switch without a specific value. In that case, each case becomes its own condition.

main.go
package main

import "fmt"

func main() {
    temperature := 30

    switch {
    case temperature >= 30:
        fmt.Println("Hot")
    case temperature >= 20:
        fmt.Println("Warm")
    case temperature >= 10:
        fmt.Println("Cool")
    default:
        fmt.Println("Cold")
    }
}
Output:Жарко
GOLANG
Output

Practice examples

To really get comfortable with conditions, it helps to solve a few simple exercises.

  • Check whether a number is positive or negative.
  • Check whether a number is even or odd.
  • Check whether a user can get access based on their age.
  • Check a user's login and password.
  • Print the name of the day of the week for a given number.

Summary

Conditional statements let a program make decisions. Without conditions you can't write a real program, because almost all logic depends on different situations.

  • if is used for a simple check;
  • else runs when the condition is false;
  • else if is for checking several options;
  • switch is handy when you need to compare a value against several options;
  • &&, ||, ! let you combine and flip conditions.
03

Lesson 3: Loops & the for Statement

What is a loop?

A loop is a sequence of instructions that lets you perform an action many times.

In programming, you very often need to repeat the same action several times. For example:

  • printing the numbers from 1 to 10;
  • calculating the sum of a set of numbers;
  • reading several values from the console;
  • processing a list of students;
  • printing a multiplication table.

Without loops you'd have to write the same code over and over by hand. Loops make code shorter, clearer, and easier to work with.

Go only has one loop — for — but it can take several different forms.

How does a loop work?

  • first, a starting value is set;
  • then the condition is checked;
  • if the condition is true, the loop's body runs;
  • after that, the value changes;
  • then the condition is checked again.

The classic for

The classic for loop is used when you roughly know in advance how many times the loop needs to run.

For example, to print the numbers from 0 to 4:

main.go
package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}
Output:0 1 2 3 4
GOLANG
Output

The loop is made up of three parts:

  • i := 0 — initialization (the starting value)
  • i < 5 — condition (the loop keeps running while this is true)
  • i++ — step (updates the variable after each iteration)

So the loop ran 5 times — until i became equal to 5.

Example: printing 1 to 10

A very common task is printing numbers within a given range. A regular for loop handles that.

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}
Output:1 2 3 4 5 6 7 8 9 10
GOLANG
Output

In this example, i starts at 1. The loop runs as long as i <= 10. After each iteration, i increases by 1.

Example: sum of numbers

Loops are often used to accumulate a result. For example, we can add up the numbers from 1 to 5.

main.go
package main

import "fmt"

func main() {
    sum := 0

    for i := 1; i <= 5; i++ {
        sum = sum + i
    }

    fmt.Println(sum)
}
Output:15
GOLANG
Output

Here, the sum variable holds the running total. On each iteration we add the current value of i to it.

How sum changes:

  • i = 1, sum = 0 + 1 = 1
  • i = 2, sum = 1 + 2 = 3
  • i = 3, sum = 3 + 3 = 6
  • i = 4, sum = 6 + 4 = 10
  • i = 5, sum = 10 + 5 = 15

Example: printing only even numbers

You can use conditionals inside a loop. For example, we can go through the numbers 1 to 10 and print only the even ones.

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i%2 == 0 {
            fmt.Println(i)
        }
    }
}
Output:2 4 6 8 10
GOLANG
Output

The condition i%2 == 0 checks whether a number divides evenly by 2. If the remainder is 0, the number is even.

for acting as while

Go doesn't have a separate while keyword. But you can use for as a while loop by leaving just the condition.

main.go
package main

import "fmt"

func main() {
    i := 1
    for i < 10 {
        fmt.Println(i)
        i++
    }
}
Output:1 2 3 4 5 6 7 8 9
GOLANG
Output

Same as before — the loop runs as long as the condition is true. Here, that means while i < 10.

The infinite loop

Writing for with no condition at all gives you an infinite loop. It keeps running forever until we stop it manually or use break.

main.go
package main

import "fmt"

func main() {
    i := 1

    for {
        fmt.Println(i)
        i++

        if i > 5 {
            break
        }
    }
}
Output:1 2 3 4 5
GOLANG
Output

Important: use infinite loops carefully. If you forget the exit condition, the program can run forever.

The break statement

break lets you exit a loop early. It's useful once you've found what you needed and don't want to keep looping.

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 6 {
            break
        }

        fmt.Println(i)
    }
}
Output:1 2 3 4 5
GOLANG
Output

Once i becomes 6, break fires. The loop ends immediately, so 6 and everything after it never gets printed.

The continue statement

continue skips the current iteration and jumps straight to the next one. It's useful when you need to skip certain values.

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            continue
        }

        fmt.Println(i)
    }
}
Output:1 2 4 5
GOLANG
Output

When i equals 3, continue runs, so fmt.Println(i) for that value gets skipped.

A loop that reads input

Loops can also be used to read data from the console. For example, we can keep reading numbers until the user enters 0.

main.go
package main

import "fmt"

func main() {
    var number int

    for {
        fmt.Scan(&number)

        if number == 0 {
            break
        }

        fmt.Println(number)
    }
}

In this example the loop runs forever, but ends once the user enters 0.

This approach is common when you don't know ahead of time how many values the user will enter.

Nested loops

A loop can live inside another loop. This is called a nested loop.

One of the most popular examples is a multiplication table.

main.go
package main

import "fmt"

func main() {
    for i := 1; i < 10; i++ {
        for j := 1; j < 10; j++ {
            fmt.Print(i*j, "\t")
        }
        fmt.Println()
    }
}
Output:1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
GOLANG
Output

This gives us a multiplication table: i runs across, j runs down. Each loop runs while its variable is less than 10.

How it works:

  • the outer loop is responsible for the rows;
  • the inner loop is responsible for the columns;
  • each iteration prints the result of i * j;
  • once the inner loop finishes, we move to a new line.

Nested loop example: a rectangle of asterisks

Nested loops are often used to draw simple shapes in the console. For example, we can print a rectangle made of * characters.

main.go
package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 5; j++ {
            fmt.Print("*")
        }
        fmt.Println()
    }
}
Output:***** ***** *****
GOLANG
Output

The outer loop runs 3 times, creating 3 rows. The inner loop runs 5 times, printing 5 asterisks on each row.

The for range loop

Go frequently uses the for range form. It comes in handy when you need to go through a collection of data.

For example, we can go through a list of names:

main.go
package main

import "fmt"

func main() {
    names := []string{"Aibek", "Dana", "Miras"}

    for index, name := range names {
        fmt.Println(index, name)
    }
}
Output:0 Aibek 1 Dana 2 Miras
GOLANG
Output

The index variable holds the element number, and the name variable holds the value itself.

When you don't need the index

Sometimes you only need the value, and the index isn't needed. In that case you can use the _ symbol instead of the index.

main.go
package main

import "fmt"

func main() {
    names := []string{"Aibek", "Dana", "Miras"}

    for _, name := range names {
        fmt.Println(name)
    }
}
Output:Aibek Dana Miras
GOLANG
Output

The _ symbol means we don't need that value.

Common mistakes when working with loops

  • forgetting to update the loop variable;
  • writing a condition that is always true;
  • creating an infinite loop with no break;
  • getting the loop bounds wrong;
  • mixing up < and <=.

Mini practice

To really get comfortable with loops, try writing programs for the following tasks:

  • print the numbers from 1 to 100;
  • print only the odd numbers from 1 to 50;
  • calculate the sum of numbers from 1 to N;
  • print the multiplication table for a single number;
  • read numbers until the user enters 0;
  • find the largest number among the ones entered;
  • print a square made of * characters.

Summary

Loops let you run the same code many times. Go only has the for loop for this, but it can be written in several forms:

  • the classic for is handy when the loop bounds are known;
  • for as while is handy when only the condition check matters;
  • an infinite for is used together with break;
  • break ends the loop;
  • continue skips the current iteration;
  • nested loops let you work with tables and shapes;
  • for range is used to walk through collections of data.
04

Lesson 4: Slices

What is a slice?

A slice is a sequential collection of elements of the same type. Unlike arrays, slices have a dynamic length: you can add new elements to them and remove existing ones.

Slices are very similar to arrays, but much more convenient in real development. While an array has a fixed size, a slice can grow as needed.

That's why in Go, people usually work with slices rather than plain arrays.

Slices are like a Kazakh toi (a big celebration): you can plan an event for 200 people, but how many guests actually show up in the end is anyone's guess. Maybe 150? 250? Or a full 300? Slices have the same quality as toi organizers — flexibility.

Meiram "Punctuality" Toibastarov — the guy who "never" shows up late, and knows a thing or two about slices

The main difference between a slice and an array — a slice's length can change while the program is running.

Array vs slice

Visually, an array and a slice look very similar, but there's an important difference between them.

Array

Fixed size. If an array is created for 5 elements, it will always contain exactly 5 elements.

Slice

Dynamic size. You can add elements to a slice and get a new, bigger slice.

In Go, a slice is written almost like an array, just without specifying a size inside the square brackets.

Creating a slice

Slices are created almost like arrays, just without specifying a length.

Main.go
package main

import "fmt"

func main() {
    boxers := []string{"Muhammad Ali", "Mike Tyson", "George Foreman", "Joe Frazier"}
    for _, value := range boxers {
        fmt.Println(value)
    }
}
Output:Muhammad Ali Mike Tyson George Foreman Joe Frazier
GOLANG
Output

Notice: inside [] we didn't specify a length — that's exactly why this is a slice.

If you write [4]string, that's an array. If you write []string, that's a slice.

Slices of different types

A slice can store elements of different data types, but inside one slice all elements must be of the same type.

A slice of numbers:

numbers := []int{10, 20, 30, 40}

A slice of strings:

cities := []string{"Almaty", "Astana", "Paris"}

A slice of booleans:

answers := []bool{true, false, true}

Creating a slice with make()

Slices can also be created using the make() function:

Main.go
package main

import "fmt"

func main() {
    cities := make([]string, 4)
    cities[0] = "Almaty"
    cities[1] = "Astana"
    cities[2] = "New-York"
    cities[3] = "Washington"

    for _, value := range cities {
        fmt.Println(value)
    }
}
Output:Almaty Astana New-York Washington
GOLANG
Output

When we write make([]string, 4), Go creates a slice of strings with length 4. After that, we can access elements by indices from 0 to 3.

Now let's look at how to add and remove elements, and what the slice operator is.

Length and capacity: len and cap

A slice has two important characteristics: length and capacity.

  • len — how many elements are currently in the slice;
  • cap — how many elements fit in the current underlying array.
Main.go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30}

    fmt.Println(len(numbers))
    fmt.Println(cap(numbers))
}
Output:3 3
GOLANG
Output

At first, len and cap are often equal. But after adding elements with append, the capacity may change.

Adding elements (append)

The append(slice, value) function is used to add an element to a slice.

Main.go
package main

import "fmt"

func main() {
    cities := []string{"Almaty", "Astana"}

    cities = append(cities, "Paris")
    cities = append(cities, "Marcel")

    for _, value := range cities {
        fmt.Println(value)
    }
}
Output:Almaty Astana Paris Marcel
GOLANG
Output

It's important to save the result back into the variable: cities = append(cities, "Paris"). The append function returns a new slice.

Adding several elements

You can add several elements at once through append.

Main.go
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}

    numbers = append(numbers, 4, 5, 6)

    fmt.Println(numbers)
}
Output:[1 2 3 4 5 6]
GOLANG
Output

Adding one slice into another

Sometimes you need to add not one value, but all the elements of another slice. The ... operator is used for this.

Main.go
package main

import "fmt"

func main() {
    first := []int{1, 2, 3}
    second := []int{4, 5, 6}

    first = append(first, second...)

    fmt.Println(first)
}
Output:[1 2 3 4 5 6]
GOLANG
Output

The three dots ... unpack the second slice into a set of separate elements.

The slice operator (s[i:j])

The slice operator looks like this: s[i:j], where:

  • s — the source slice
  • i — the starting index (inclusive)
  • j — the ending index (exclusive)
Index Value
0 Almaty
1 Astana
2 New-York
3 Washington

For example, if you write cities[0:2], you get the elements at indices 0 and 1. The element at index 2 is no longer included in the result.

Main.go
package main

import "fmt"

func main() {
    cities := []string{"Almaty", "Astana", "New-York", "Washington", "Paris", "Marcel"}

    kzCities := cities[0:2]
    usaCities := cities[2:4]
    frCities := cities[4:6]

    fmt.Println(kzCities)  // Almaty, Astana
    fmt.Println(usaCities) // New-York, Washington
    fmt.Println(frCities)  // Paris, Marcel
}
Output:[Almaty Astana] [New-York Washington] [Paris Marcel]
GOLANG
Output

Short slice forms

In Go, you can leave out the starting or ending index.

  • s[:3] — take elements from the start up to index 3, not including 3;
  • s[2:] — take elements from index 2 to the end;
  • s[:] — take the whole slice.
Main.go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}

    fmt.Println(numbers[:3])
    fmt.Println(numbers[2:])
    fmt.Println(numbers[:])
}
Output:[10 20 30] [30 40 50] [10 20 30 40 50]
GOLANG
Output

Changing a slice element

Just like with arrays, slice elements can be changed by index.

Main.go
package main

import "fmt"

func main() {
    cities := []string{"Almaty", "Astana", "Paris"}

    cities[2] = "London"

    fmt.Println(cities)
}
Output:[Almaty Astana London]
GOLANG
Output

Here, the element at index 2 was changed from Paris to London.

Removing an element

Removal is usually done by combining append with the slice operator. We take the elements before the index and the elements after the index, then "glue" them together.

Main.go
package main

import "fmt"

func main() {
    capitals := []string{"Astana", "Washington", "Marcel", "Paris"}

    num := 2 // remove the element at index 2 (Marcel)
    capitals = append(capitals[:num], capitals[num+1:]...)
    fmt.Println(capitals)
}
Output:[Astana Washington Paris]
GOLANG
Output

Important: capitals[:num] is the elements before num, and capitals[num+1:] is the elements after num. The three dots ... "unpack" the slice as a set of arguments.

How this works:

  • capitals[:2] gives [Astana Washington];
  • capitals[3:] gives [Paris];
  • append joins these parts;
  • the element Marcel disappears from the result.

Looping over a slice with range

Slices are convenient to loop over with range. We can get both the index and the value.

Main.go
package main

import "fmt"

func main() {
    cities := []string{"Almaty", "Astana", "Paris"}

    for index, value := range cities {
        fmt.Println(index, value)
    }
}
Output:0 Almaty 1 Astana 2 Paris
GOLANG
Output

When you don't need the index

If you only need the element, you can replace the index with _.

Main.go
package main

import "fmt"

func main() {
    cities := []string{"Almaty", "Astana", "Paris"}

    for _, value := range cities {
        fmt.Println(value)
    }
}
Output:Almaty Astana Paris
GOLANG
Output

Example: sum of slice elements

Slices are often used together with loops. For example, we can calculate the sum of all the numbers in a slice.

Main.go
package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40}
    sum := 0

    for _, value := range numbers {
        sum = sum + value
    }

    fmt.Println(sum)
}
Output:100
GOLANG
Output

Example: finding the maximum number

Using a loop and a slice, we can find the maximum number.

Main.go
package main

import "fmt"

func main() {
    numbers := []int{15, 90, 12, 45, 7}
    max := numbers[0]

    for _, value := range numbers {
        if value > max {
            max = value
        }
    }

    fmt.Println(max)
}
Output:90
GOLANG
Output

Common mistakes when working with slices

  • forgetting to save the result of append back into the variable;
  • accessing an index that doesn't exist in the slice;
  • mixing up an array [5]int and a slice []int;
  • forgetting that the ending index in s[i:j] is not included;
  • forgetting to add ... when adding one slice into another.

Mini practice

To get comfortable with slices, try writing programs for the following tasks:

  • create a slice of 5 numbers and print all the elements;
  • add a few more numbers to the slice using append;
  • print only the first 3 elements of the slice;
  • print the elements from index 2 to the end;
  • remove an element by index;
  • calculate the sum of all the elements;
  • find the maximum number;
  • print only the positive numbers.

Key takeaways

  • a slice looks like an array, but has a dynamic length;
  • a slice is created with []type, without specifying a size;
  • make lets you create a slice of a given length;
  • append adds new elements;
  • s[i:j] gives you part of a slice;
  • the ending index in s[i:j] is not included;
  • elements can be changed by index;
  • removal can be done using append and the slice operator;
  • range is convenient for looping over a slice.

Leave a Request

Leave your details and our admissions team will call you back to help pick the right course.

By submitting this form you agree to be contacted by BITLAB Academy about your request.