liveBook · Manning

Slicing

As explained in Go in Practice, Second Edition

Slicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.

A Go slice is a variable-length collection, useful for homogeneous data. Slices can hold valid command-line options, receive non-flag arguments, and provide input to functions that process items. section 2.1.2 section 2.1.3

validLanguages = []string{
    "en",
    "sp",
    "fr",
    "de",
}

func init() {
    flag.StringVar(&userLanguage, "lang", "en", "language 
    to use (en, sp, fr, de).")
    flag.Parse()
    if slices.Contains(validLanguages, userLanguage) == false {
log.Fatalf("Invalid language %s. Please use one of %v", 
userLanguage, validLanguages)
    }
}

A slice of language codes makes the permitted command-line values explicit and supports rejecting invalid input. section 2.1.2

Listing 3.9 Implementing a filter function
package main

import (
    "fmt"
    "unicode"
)

func filter[T any](items []T, fx func(T) bool) []T {     #1
    var filtered []T
    for _, v := range items {
        if fx(v) {
            filtered = append(filtered, v)
        }
    }
    return filtered
}

func main() {
    strings := []string{"My", "name", "is", "Inigo", "Montoya"}

    strings = filter[string](strings, func(s string) bool {      #2
        return unicode.IsUpper(rune(s[0]))
    })

    fmt.Println(strings)
}

go run generic.go
[My Inigo Montoya]

A generic filter loops over a slice and returns the items that pass a callback, here selecting strings that begin with uppercase letters. section 3.4.1

How Go in Practice, Second Edition covers it

How deep it goes
Defines slices against arrays and demonstrates validation and filtering, without detailing range expressions or slice internals.
Examples
Demonstrates validating language codes and filtering slices of strings and integers.
What you can do after
Apply slices to validate allowed values and filter collections with generic functions.
How it connects
Connects slices to arrays, maps, command-line flags, and generics.

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.