Thuta Learning
IntermediateProgrammingbeginner

Slices

Relax. We'll talk through this in plain words — no textbook voice.

Slice is the most commonly used collection type in Go. It's more flexible than an array, and you can use append to add new data. You'll see slices anywhere the amount of data can change — lists, search results, user records, and more.

go
package main

import "fmt"

func main() {
    languages := []string{"Go", "JavaScript", "PHP"}
    languages = append(languages, "Python")

    for index, language := range languages {
        fmt.Println(index, language)
    }
}

[]string{...} builds a string slice. append adds a new item and returns a new slice, so you need to store the result back into the variable.

You should see
0 Go 1 JavaScript 2 PHP 3 Python

Info

range gives you both the index and the value. If you don't need the index, _ lets you ignore it.

Easy traps

  • If you just write append(languages, "Python") without reassigning it back to languages =, the data won't change the way you expect.
Slices | Thuta Learning