Junior — Middle
Kas saaksid anda näiteid olukordadest, kus programmeerimiskeeles kasutatakse tüübi kinnitust (Type Assertion)?
sobes.tech AI
Vastus AI-lt
In Go, Type Assertion is used to extract 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 specific type you want to work with.
Examples of usage:
- Extracting a specific type from an interface to call specific methods.
- Processing values returned from functions that return an interface.
- When you need to check if a variable implements a certain type, and perform the appropriate 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")
}
Performing type assertion without check, if the type does not match, the program will panic.