Different Ways to Find the Type of an Object in Golang


Golang is a statically typed language, which means that the data types of variables are defined at the time of declaration. It is important to know the type of an object or variable when developing software applications. In this article, we will explore different ways to find the type of an object in Golang.

Using the Reflect Package

The reflect package in Golang provides a way to inspect the types of variables. The TypeOf function in the reflect package returns a Type object that represents the type of the given value.

Example

package main

import (
   "fmt"
   "reflect"
)

func main() {
   var x int = 10
   fmt.Println(reflect.TypeOf(x))
}

Output

int

Using the fmt Package

The fmt package in Golang provides a verb called %T, which prints the type of a variable.

Example

package main

import (
   "fmt"
)

func main() {
   var x int = 10
   fmt.Printf("Type of x is %T", x)
}

Output

Type of x is int

Using the Switch Statement

The switch statement in Golang can be used to find the type of an object. We can use the type keyword with the switch statement to check the type of a variable.

Example

package main

import (
   "fmt"
)

func findType(i interface{}) {
   switch i.(type) {
   case int:
      fmt.Println("Type of i is int")
   case float64:
      fmt.Println("Type of i is float64")
   case string:
      fmt.Println("Type of i is string")
   default:
      fmt.Println("Unknown type")
   }
}

func main() {
   var x int = 10
   findType(x)
}

Output

Type of i is int

Conclusion

In this article, we explored different ways to find the type of an object in Golang. We used the reflect package, fmt package, and the switch statement to find the type of a variable. All of these methods are useful in different scenarios, depending on the requirements of the software application.

Updated on: 12-Apr-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements