Go – Type Assertion Explained with Syntax, Examples & Use Cases (2025 Guide)
Introduction – What Is Type Assertion in Go?
In Go, type assertion is used to extract the underlying concrete value from an interface{} variable. It allows you to convert an interface type to its actual type—safely or unsafely. Type assertion is widely used in generic interfaces, JSON decoding, and polymorphic behavior.
In this section, you’ll learn:
- How to use type assertion syntax in Go
- Perform safe vs unsafe type assertions
- Use
type switchesfor multiple type handling - Real-world examples and common pitfalls
Basic Type Assertion Syntax
var i interface{} = "GoLang"
str := i.(string)
fmt.Println(str)
Output:
GoLang
Here, i.(string) asserts that the underlying type stored in i is a string.
Unsafe Assertion – Runtime Panic
var i interface{} = 123
str := i.(string) // This will panic
Output:
panic: interface conversion: interface {} is int, not string
Use only when you’re absolutely sure of the type.
Safe Assertion Using Comma-Ok Idiom
var i interface{} = "Hello"
str, ok := i.(string)
if ok {
fmt.Println("String value:", str)
} else {
fmt.Println("Not a string")
}
Output:
String value: Hello
Avoids panic—ok returns true if assertion is valid.
Type Switch – Handle Multiple Types Safely
var val interface{} = 3.14
switch v := val.(type) {
case int:
fmt.Println("Integer:", v)
case float64:
fmt.Println("Float:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
Output:
Float: 3.14
The type switch simplifies checking multiple possible types.
Real-World Use – JSON Decoding
data := map[string]interface{}{
"age": 30,
"name": "John",
}
age, ok := data["age"].(int)
name, ok2 := data["name"].(string)
fmt.Println("Age:", age, "Name:", name)
Commonly used when decoding interface{} maps returned from JSON.
Type Assertion vs Type Conversion
| Feature | Type Assertion | Type Conversion |
|---|---|---|
| Works on | interface{} types | Any compatible types |
| Purpose | Extract real type | Convert value types |
| Syntax | val.(T) | T(val) |
| Fails if mismatched? | Runtime panic | Compile-time error |
Best Practices
- Always use comma-ok idiom unless you’re sure of the type
- Use
type switchfor multi-type logic - Avoid overusing
interface{}unless necessary - Keep interfaces small and focused for easy type assertions
Summary – Recap & Next Steps
Type assertion is a vital tool in Go for extracting the real type from interface variables. It enables safe type conversion and is widely used in generic programming and decoding dynamic data.
Key Takeaways:
- Use
i.(T)to assert type - Use
i.(T), okto avoid panics - Use
type switchto handle multiple types - Validate types when decoding from
interface{}
Next: Explore Go Reflection, Interface Composition, or Generics with type constraints.
FAQs – Go Type Assertion
What happens if type assertion fails?
It causes a runtime panic, unless handled with the comma-ok idiom.
How is type assertion different from type conversion?
Type assertion extracts the underlying value from an interface{}. Conversion changes one value type to another.
When should I use a type switch?
Use a type switch when checking for multiple possible types.
Can I assert to a struct type?
Yes, as long as the interface holds a value of that struct type.
Is type assertion available for all interfaces?
Yes, but it only works if the underlying type matches the asserted type.
Share Now :
