Code-Memo

Generics and reflection

Python metaclasses change class creation. The closest Go themes are generics (compile-time type parameters) and reflect (runtime type inspection).

Generics (type parameters)
func MapKeys[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
}

comparable is required for map keys and ==. Constraints can be interfaces listing method sets or unions of types.

Common generic patterns
reflection
import "reflect"

func describe(v any) {
	rv := reflect.ValueOf(v)
	rt := rv.Type()
	_ = rt.Kind()
}

Reflection is verbose, loses compile-time checks, and can be slower — use for encoding (encoding/json), dependency injection frameworks, or generic serializers.

Code generation

For repetitive boilerplate without generics, go generate with tools like stringer is idiomatic.

When not to use reflection

If types are known at compile time, normal functions and interfaces are clearer and safer.