Programming Languages
Go
Subjective
Oct 04, 2025
Explain type assertions and type switches.
Detailed Explanation
Type Assertions and Type Switches:
• Type assertion extracts interface's underlying value
• Type switch tests interface against multiple types
• Used with interface{} and other interfaces
• Can panic if assertion fails
Type Assertion:
var i interface{} = "hello"
s := i.(string) // panics if not string
s, ok := i.(string) // safe version
Type Switch:
switch v := i.(type) {
case string:
fmt.Println("String:", v)
case int:
fmt.Println("Int:", v)
default:
fmt.Println("Unknown type")
}
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts