In Go, you can use the reflect
package to inspect the type of a variable at runtime.
Here's an example of how to use reflection to inspect the type of a variable:
package main
import (
"fmt"
"reflect"
)
func main() {
var num int = 42
var str string = "hello"
var boolean bool = true
fmt.Println("Variable:", num)
getType(num)
fmt.Println("Variable:", str)
getType(str)
fmt.Println("Variable:", boolean)
getType(boolean)
}
func getType(variable interface{}) {
fmt.Println("Type:", reflect.TypeOf(variable))
}
In the getType
function, we pass the variable we want to inspect as an interface{}
type. Then, using reflect.TypeOf(variable)
, we get the reflect.Type
of the variable. Finally, we print the type using fmt.Println
.
When you run this code, you'll see the type of each variable printed to the console:
Variable: 42
Type: int
Variable: hello
Type: string
Variable: true
Type: bool
Note that reflection should be used sparingly in Go since it can have a negative impact on performance and readability. It's usually better to rely on Go's static typing to ensure correct variable types.