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















