How to find a type of an object in Go?

In Go, you can use the reflect package to find the type of an object at runtime. The reflect package provides a set of functions and types for runtime reflection, allowing you to inspect the underlying type and properties of variables and values.

Here’s how you can find the type of an object in Go using reflection:

package main

import (

func main() {
    // Sample variables of different types
    var num int = 42
    var str string = "Hello, Go!"
    var arr = [3]int{1, 2, 3}
    var myMap = map[string]int{"a": 1, "b": 2}

    // Using reflection to find the type of each object
    fmt.Println("Type of num:", reflect.TypeOf(num))
    fmt.Println("Type of str:", reflect.TypeOf(str))
    fmt.Println("Type of arr:", reflect.TypeOf(arr))
    fmt.Println("Type of myMap:", reflect.TypeOf(myMap))


Type of num: int
Type of str: string
Type of arr: [3]int
Type of myMap: map[string]int

In the example above, we import the reflect package and use the reflect.TypeOf() function to find the type of different variables (num, str, arr, and myMap). The function returns a reflect.Type value that represents the type of the variable.

Please note that reflection is a powerful feature, but it comes with a performance cost, and it should be used judiciously. Reflection is typically used in scenarios where you need to work with unknown or dynamically-typed values, implement generic algorithms, or handle custom data structures at runtime. In most cases, Go’s static typing system is sufficient for type safety and performance.

error: Content is protected !!