Compare generics interfaces and reflection
Compare generics interfaces and reflection
Use generics when the same algorithm needs type-preserving operations over several types. Use basic interfaces when consumers need interchangeable behavior through methods. Reflection inspects types or values at runtime and is useful when the shape is unknown until execution. These tools can coexist; choose the simplest contract that meets the need.
package main
import ( "fmt")
func head[T any](xs []T) (T, bool) { if len(xs) == 0 { var zero T return zero, false } return xs[0], true}func main() { v, ok := head([]int{5, 6}) fmt.Printf("%T %d %t\n", v, v, ok)}The result is statically int, not any. A caller does not need a runtime assertion. The boolean distinguishes absence from a present zero value. No claim about relative speed follows from the syntax alone.
Expected output:
int 5 trueBehavior versus runtime inspection
package main
import ( "fmt" "reflect")
type Named interface{ Name() string }type Item struct{ Label string }
func (i Item) Name() string { return i.Label }func show(n Named) { fmt.Println(n.Name()) }func main() { i := Item{Label: "pen"} show(i) fmt.Println(reflect.TypeOf(i).Name())}Named exposes behavior regardless of the concrete type. reflect.TypeOf returns type information at runtime; it does not replace the interface contract. Its result is nil for a nil interface, so inspect it before calling methods if nil is possible. Prefer static types or interfaces when the needed operations are already known.
Expected output:
penItemTry it locally
Write a generic duplicate function returning []T with two copies of v. Use a string argument and print the slice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 09: Compare generics interfaces and reflection
Check the lesson objective before moving on.
Which tool is natural for preserving the input element type in a reusable slice algorithm?
What does reflection inspect?