golang

How to check typeOf a variable in Golang


In this article, you are going to learn about how to check typeof variable in Golang.

Like other programming languages, Golang has different types of variables. such as integer, string, and so on. To check a variable type, GoLang provides a reflection package. With the help of this package, you can easily detect a variable type. Follow the code example below;

import (
        "fmt"
        "reflect"
)
func main() {
        val1 := "string"
        val2 := 10
        val3 := 1.2
        val4 := true
        val5 := []string{"deven", "alex", "rathore"}
        val6 := map[string]int{"age": 21, "id": 43}

        fmt.Println(reflect.TypeOf(val1))
        fmt.Println(reflect.TypeOf(val2))
        fmt.Println(reflect.TypeOf(val3))
        fmt.Println(reflect.TypeOf(val4))
        fmt.Println(reflect.TypeOf(val5))
        fmt.Println(reflect.TypeOf(val6))

}

/*Output:
        string
        int
        float64
        bool
        []string
        map[string]int
*/

We first import our required packages and then implement our code to see the type of a variable and you can see the output with different variable types names.

You can use reflect.ValueOf().kind() instead of using reflect.TyoeOf() and get the same result as well. See the following code below:


package main

import (
        "fmt"
        "reflect"
)
func main() {
        val1 := "string"
        val2 := 10
        val3 := 1.2
        val4 := true
        val5 := []string{"deven", "alex", "rathore"}
        val6 := map[string]int{"age": 21, "id": 43}

        fmt.Println(reflect.ValueOf(val1).Kind())
        fmt.Println(reflect.ValueOf(val2).Kind())
        fmt.Println(reflect.ValueOf(val3).Kind())
        fmt.Println(reflect.ValueOf(val4).Kind())
        fmt.Println(reflect.ValueOf(val5).Kind())
        fmt.Println(reflect.ValueOf(val6).Kind())

}
/*Output:
        string
        int
        float64
        bool
        slice
        map
*/

If these two way seems complex to you, you can simply use %T\n and the name of the variable. In that case, you have to type Printf and a \n to print the output in the next line. See the code example below:

package main

import (
        "fmt"
)
func main() {
        val1 := "string"
        val2 := 10
        val3 := 1.2
        val4 := true
        val5 := []string{"deven", "alex", "rathore"}
        val6 := map[string]int{"age": 21, "id": 43}

        fmt.Printf("%T\\n", val1)
        fmt.Printf("%T\\n", val2)
        fmt.Printf("%T\\n", val3)
        fmt.Printf("%T\\n", val4)
        fmt.Printf("%T\\n", val5)
        fmt.Printf("%T\\n", val6)

}

/*Output:
        string
        int
        float64
        bool
        []string
        map[string]int
*/

This is all about How to check typeOf a variable in Golang.


Share on social media

//