1.

How will you check the type of a variable at runtime in Go?

Answer»

In GO, we can USE a special type of switch for checking the VARIABLE type at runtime. This switch statement is called a “type switch”.

Consider the following piece of code where we are checking for the type of variable v and performing some set of operations.

switch v := param.(type) { DEFAULT: fmt.Printf("Unexpected type %T", v)case uint64: fmt.Println("Integer type")case string: fmt.Println("String type")}

In the above code, we are checking for the type of variable v, if the type of variable is uint64, then the code prints “Integer type”. If the type of variable is a string, the code prints “String type”. If the type doesn't MATCH, the default block is executed and it runs the statements in the default block.



Discussion

No Comment Found