in go, you can check if an interface value holds a specific concrete type using type assertions—concise, efficient, and idiomatic—without resorting to reflection or verbose type switches.
When working with interface{} values, Go doesn’t support direct type comparison like reflect.TypeOf(x) == int (which is invalid syntax—int is not a type value, and reflect.Type requires proper comparison via reflect.TypeOf(x).Kind() == reflect.Int or reflect.TypeOf(x) == reflect.TypeOf(int(0))). Instead, the idiomatic and recommended approach is a type assertion with comma-ok idiom, which safely tests and optionally extracts the underlying value.
Here’s how it works:
var x interface{} = 42
// Type assertion: attempt to convert x to int
if _, ok := x.(int); ok {
fmt.Println("x holds an int")
} else {
fmt.Println("x does not hold an int")
}
This evaluates to true only if x’s dynamic type is exactly int (not just assignment-compatible, but concrete int). Note that this checks for the exact type, not underlying kind — so int8, int32, or int64 will all fail the x.(int) assertion.
✅ Advantages over alternatives: