Golang Code

Print a Variable's Type (e.g. Int, String, Float)

· 107 words · 1 minute read #type #reflect #variable #package #printf

Ever wanted to know the exact type name of the variable you’re using? The Printf is capable of print exactly this information back out to you, like so:

package main

import "fmt"

func main() {
    // Will print 'int'
    anInt := 1234
    fmt.Printf("%T\n", anInt)

    // Will print 'string'
    aString := "Hello World"
    fmt.Printf("%T\n", aString)

    // Will print 'float64'
    aFloat := 3.14
    fmt.Printf("%T\n", aFloat)
}

Alternatively, you can also use the reflect package. The TypeOf function will return a Type but we convert this to a string with .String().

package main

import (
    "fmt"
    "reflect"
)

func main() {
    // Will print 'int'
    anInt := 1234
    fmt.Println(reflect.TypeOf(anInt).String())
}
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!