Lab 06: Generics
Overview
Step 1: Generic Functions
package main
import "fmt"
// T is a type parameter, any is the constraint
func Contains[T comparable](s []T, item T) bool {
for _, v := range s {
if v == item {
return true
}
}
return false
}
func Keys[K comparable, V any](m map[K]V) []K {
keys := make([]K, 0, len(m))
for k := range m {
keys = append(keys, k)
}
return keys
}
func main() {
fmt.Println(Contains([]int{1, 2, 3}, 2)) // true
fmt.Println(Contains([]string{"a", "b"}, "c")) // false
m := map[string]int{"x": 1, "y": 2}
fmt.Println(Keys(m)) // [x y] (order may vary)
}Step 2: Type Constraints
Step 3: Generic Types
Step 4: Generic Map / Filter / Reduce
Step 5: Type Inference
Step 6: The slices Package (Go 1.21)
Step 7: Generic Option Type
Step 8: Capstone — Generic Priority Queue
Summary
Concept
Syntax
Notes
Last updated
