How to find the type of a variable in Golang

In Golang, we can find the type of a variable using:

  • The TypeOf function within the reflect package
  • The ValueOf.Kind function within the reflect package
  • The %T and Printf functions within the fmt package

The reflect.TypeOf() function

The reflect.TypeOf() function accepts a variable as a parameter and returns its type.

The code snippet given below shows us how to find the type of a variable, using this function:

package main
import (
"fmt"
"reflect"
)
func main() {
// string
var variable1 string
// integer
var variable2 int
// float64
var variable3 float64
// bool
var variable4 bool
// slice
var variable5 = []string{}
fmt.Println("Type of variable1:",reflect.TypeOf(variable1))
fmt.Println("Type of variable2:",reflect.TypeOf(variable2))
fmt.Println("Type of variable3:",reflect.TypeOf(variable3))
fmt.Println("Type of variable4:",reflect.TypeOf(variable4))
fmt.Println("Type of variable5:",reflect.TypeOf(variable5))
}

The reflect.ValueOf().Kind() function

The reflect.ValueOf() function accepts a variable as a parameter. By appending the Kind() function to it, we can get the type of that variable.

The code snippet given below shows us how to find the type of a variable, using this function:

package main
import (
"fmt"
"reflect"
)
func main() {
// string
var variable1 string
// integer
var variable2 int
// float64
var variable3 float64
// bool
var variable4 bool
// slice
var variable5 = []string{}
fmt.Println("Type of variable1:",reflect.ValueOf(variable1).Kind())
fmt.Println("Type of variable2:",reflect.ValueOf(variable2).Kind())
fmt.Println("Type of variable3:",reflect.ValueOf(variable3).Kind())
fmt.Println("Type of variable4:",reflect.ValueOf(variable4).Kind())
fmt.Println("Type of variable5:",reflect.ValueOf(variable5).Kind())
}

The %T and Printf() function

The fmt.Printf() function contains a format type %T that represents the type of a variable.

The code snippet given below shows us how to find the type of a variable, using this function:

package main
import (
"fmt"
)
func main() {
// string
var variable1 string
// integer
var variable2 int
// float64
var variable3 float64
// bool
var variable4 bool
// slice
var variable5 = []string{}
fmt.Printf("Type of variable1: %T\n", variable1)
fmt.Printf("Type of variable2: %T\n", variable2)
fmt.Printf("Type of variable3: %T\n", variable3)
fmt.Printf("Type of variable4: %T\n", variable4)
fmt.Printf("Type of variable5: %T\n", variable5)
}

Free Resources