Golang: Find the type of the variable

The Go reflection package has methods for inspecting the type of variables. The following snippet will print out the reflection type of

Share on:  
                 

Golang: Find the type of the variable

The Go reflection package has methods for inspecting the type of variables. The following snippet will print out the reflection type of a string, integer and float. Document https://golang.org/pkg/reflect/#Type

package main

import (
    "fmt"
    "reflect"
)

func main() {
    b := true
    s := ""
    n := 1
    f := 1.0
    a := []string{"foo", "bar", "baz"}

    fmt.Println(reflect.TypeOf(b))
    fmt.Println(reflect.TypeOf(s))
    fmt.Println(reflect.TypeOf(n))
    fmt.Println(reflect.TypeOf(f))
    fmt.Println(reflect.TypeOf(a))
}

How to print variable type

The Printf is capable of print exactly variable type using %T formatting

package main

import fmt

func main() {
 // Will print ‘int’
 anInt := 39045843
 fmt.Printf(%T\n, anInt)

// Will print ‘string’
 aString := Hello Go Lang
 fmt.Printf(%T\n, aString)

// Will print ‘float64’
 aFloat := 12.234
 fmt.Printf(%T\n, aFloat)
}
Tags:   GOGO LANG