How to Print Data Type in Golang Console

Formatting integers and strings are simple yet powerful process to show data to users. Using the fmt package, you can format numbers and strings padded with spaces or zeroes, in different bases, and with optional quotes.

The fmt package functions accept the template string that includes the text you need to format plus other annotation verbs and returns the formatted output.

Printing data types is an essential aspect of programming, and we will see how to print data types in Go.

Golang print type

To print a type in Golang, use the %T verb in the fmt.Printf() function. The fmt.Printf() is a built-in function that formats and writes to standard output.

package main

import (
  "fmt"
)

func main() {
  var_data := "KB19"
  
  fmt.Printf("The type of variable is : %T\n", var_data)
}

In this example, we printed the string data type of a variable using the %T verb in fmt.Printf() function.

Printing type using reflect.TypeOf()

The reflect.TypeOf() function accepts an input whose data type a user wants to know, and it returns its data type, and we can print it using the fmt.Print() function.

package main

import (
  "fmt"
  "reflect"
)

func main() {
  var_data := "KB19"
  fmt.Print(reflect.TypeOf(var_data), "\n")
}

Output

string

You can see that the reflect.TypeOf() function with Print() function prints the data type of a variable in the console.

Conclusion

The best way to print the variable data type in Go is to use the %T verb in the fmt.Printf() function.

Use the reflect.TypeOf() function when necessary because it uses complex and expensive runtime reflection.

That’s it.

Leave a Comment