In Go, to print the type of a variable, you can use the TypeOf function from the reflect package. reflect.TypeOf returns a reflect.Type object representing the type of the variable. It is commonly used in conjunction with the fmt package to output type information. Here is a specific example:
gopackage main import ( "fmt" "reflect" ) func main() { // Define several variables of different types var a int = 10 var b float64 = 3.14 var c string = "hello" var d bool = true // Print the type of each variable fmt.Println("Type of a:", reflect.TypeOf(a)) fmt.Println("Type of b:", reflect.TypeOf(b)) fmt.Println("Type of c:", reflect.TypeOf(c)) fmt.Println("Type of d:", reflect.TypeOf(d)) }
In this example, we define four variables of different types: integers, floating-point numbers, strings, and booleans. By using the reflect.TypeOf function, we can obtain the type of each variable and print it using fmt.Println. This method is particularly useful during debugging, especially when you need to confirm variable types or when working with interfaces and reflection.
Running the above code will output:
shellType of a: int Type of b: float64 Type of c: string Type of d: bool
Each output clearly displays the type of the corresponding variable. This technique is very practical in development, especially when dealing with complex data structures and interfaces, as it allows for quick identification and confirmation of data types.