Junior — Middle
Can you give examples of situations where type assertion is used in programming languages?
sobes.tech AI
Answer from AI
In Go, type assertion is used to obtain a specific type from an interface value. This is useful when you have a variable of type interface{}, and you know that it contains a particular type you want to work with.
Examples of usage:
- Extracting a specific type from an interface to call type-specific methods.
- Handling values returned from functions that return an interface.
- Checking whether a variable implements a certain type and executing corresponding logic.
Code example:
var i interface{} = "hello"
// Type assertion with check
s, ok := i.(string)
if ok {
fmt.Println("String:", s)
} else {
fmt.Println("Not a string")
}
If you perform a type assertion without checking and the type does not match, the program will panic.