Skip to main content
In this article, you’ll learn how to determine the data type of a variable in Go. We cover two primary techniques: using the %T format specifier with fmt.Printf and using the reflect package’s TypeOf function, which can also handle literal values.

Using the %T Format Specifier

The simplest way to discover a variable’s data type in Go is by using the %T format specifier with fmt.Printf. In the example below, four variables of different types (integer, string, boolean, and float) are declared. Their values and corresponding data types are then printed.
To run the above program, use the following command:
The expected output will be:

Using the reflect.TypeOf Function with Literals

The reflect package’s TypeOf function is a powerful alternative that works with both variables and literals. In this example, the code shows how to determine the data types of various literals.
Run the program with:
The output is as follows:

Using the reflect.TypeOf Function with Variables

You can also pass variables into the reflect.TypeOf function to determine their data types. The following example declares two variables and prints both their values and their types.
Execute the program with:
The expected output is:

Understanding the data type of variables and literals is essential when debugging or optimizing your Go programs.
That’s it for this tutorial. In this lesson, you explored two methods to determine the data type of a variable or a literal in Go using both the %T format specifier and the reflect.TypeOf function. Keep practicing and see you in the next article!

Watch Video