Google News
logo
Golang - Interview Questions
How do you check a variable type at runtime?
The Type Switch is the best way to check a variable’s type at runtime. The Type Switch evaluates variables by type rather than value. Each Switch contains at least one case, which acts as a conditional statement, and a default case, which executes if none of the cases are true.
 
For example, you could create a Type Switch that checks if interface value i contains the type int or string:
package main

import "fmt"

func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Double %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know  type %T!\n", v)
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}
 
Output : 
Double 21 is 42
"hello" is 5 bytes long
I don't know  type bool!
Advertisement