0 votes
in GoLang by
How do you check a variable type at runtime?

1 Answer

0 votes
by

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:

1234567891011121314151617181920

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))

Related questions

0 votes
asked Aug 19, 2022 in GoLang by john ganales
0 votes
asked Aug 19, 2022 in GoLang by john ganales
...