Choose generics, interfaces or reflection
Choose generics, interfaces or reflection
Generics preserve compile-time types while sharing an algorithm across types satisfying a constraint. Reflection discovers runtime types. Prefer typed code, interfaces and generics when the operations are known; use reflection when runtime discovery is necessary.
package main
import ( "fmt")
func first[T any](s []T) (T, bool) { if len(s) == 0 { var z T return z, false } return s[0], true}func main() { a, ok := first([]string{"tea", "milk"}) fmt.Println(a, ok) n, ok := first([]int{}) fmt.Println(n, ok)}T connects the result to the slice element type. An empty slice is handled without runtime inspection. A type parameter does not make arbitrary fields available for inspection.
Expected output:
tea true0 falseHandle an unknown runtime shape
package main
import ( "fmt" "reflect")
func countFields(x any) (int, bool) { v := reflect.ValueOf(x) if v.Kind() != reflect.Struct { return 0, false } return v.NumField(), true}func main() { n, ok := countFields(struct { A int B string }{1, "x"}) fmt.Println(n, ok) n, ok = countFields(1) fmt.Println(n, ok)}Checking Kind before NumField prevents a panic for non-struct values, including nil. Reflection adds complexity; measure performance rather than assuming it. Use an interface if inputs share known behavior.
Expected output:
2 true0 falseTry it locally
Write a generic last function that reports absence for an empty slice. Test strings and an empty int slice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 05: Choose generics, interfaces or reflection
Check the lesson objective before moving on.
Which approach preserves the element type of first?
When is reflection appropriate?