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

· 136 words · 1 minute read

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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. He loves coding, but also enjoys cycling and camping in his spare time.

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!