Junior — Middle
Is it possible to perform data type checking in the Go language?
sobes.tech AI
Answer from AI
In Go, you can perform type checking at runtime using type assertion and type switch constructs. This is useful when you have a variable of interface type (interface{}), and you need to determine its specific type.
Example with type assertion:
var i interface{} = "string"
s, ok := i.(string) // ok will be true if i is indeed a string
if ok {
fmt.Println("It's a string:", s)
} else {
fmt.Println("Not a string")
}
Example with type switch:
switch v := i.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
default:
fmt.Println("other type")
}
Thus, Go supports runtime type checking but does not have a built-in function for compile-time type checking of variables, as the language is statically typed.