Lab 06: Generics

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Generics (introduced in Go 1.18) allow you to write functions and types that work with multiple types while maintaining compile-time type safety. Go generics use type parameters and constraints.

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)
}

💡 Tip: comparable means the type supports == and !=. Use any when you don't need comparison.

Step 2: Type Constraints

Constraints restrict which types can be used as type arguments.

Step 3: Generic Types

Define data structures parameterized by type.

Step 4: Generic Map / Filter / Reduce

Step 5: Type Inference

Go can often infer type parameters from function arguments.

Step 6: The slices Package (Go 1.21)

Step 7: Generic Option Type

Step 8: Capstone — Generic Priority Queue

📸 Verified Output:

Summary

Concept
Syntax
Notes

Type parameter

func F[T any](...)

Declared in [] after name

Constraint

comparable, any, custom interface

Restricts valid type args

~T in constraint

~int matches int and named types based on int

Tilde = underlying type

Type inference

Contains(slice, item) vs Contains[int](slice, item)

Compiler infers when possible

Generic type

type Stack[T any] struct

Each field/method uses T

slices package

slices.Sort, slices.Contains, slices.Max

Go 1.21 stdlib generic helpers

cmp.Compare

Works with all ordered types

Use with slices.SortFunc

Last updated