How to find the type of a variable in Golang
In Golang, we can find the type of a variable using:
- The
TypeOffunction within thereflectpackage - The
ValueOf.Kindfunction within thereflectpackage - The
%TandPrintffunctions within thefmtpackage
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 mainimport ("fmt""reflect")func main() {// stringvar variable1 string// integervar variable2 int// float64var variable3 float64// boolvar variable4 bool// slicevar 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 mainimport ("fmt""reflect")func main() {// stringvar variable1 string// integervar variable2 int// float64var variable3 float64// boolvar variable4 bool// slicevar 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 mainimport ("fmt")func main() {// stringvar variable1 string// integervar variable2 int// float64var variable3 float64// boolvar variable4 bool// slicevar 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)}