W3Basic Logo

Find the Type of an Object in Go

In this article, we will take a look at several ways to find the type of an object in Go, including using the reflect package, the fmt package, and interface{}. We will explore each method in detail with examples.


Using the reflect package:

The reflect.TypeOf function returns the reflection Type of the value passed as an argument. This method is useful when you want to get the exact type of the variable, including the package path if it's a named type.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var x int = 100
    var y float32 = 3.14
    var z string = "Hello Golang"
    var isEnabled bool = false
    fmt.Println(reflect.TypeOf(x))         // Output: int
    fmt.Println(reflect.TypeOf(y))         // Output: float32
    fmt.Println(reflect.TypeOf(z))         // Output: string
    fmt.Println(reflect.TypeOf(isEnabled)) // Output: bool
}

Output

int
float32
string
bool

Using the %T verb in the fmt package:

The %T verb in the fmt.Printf function returns the type of the variable passed as an argument. This method is useful when you want to get the type of a variable in a formatted string.

package main

import (
    "fmt"
)

func main() {
    var x int = 100
    var y float32 = 3.14
    var z string = "Hello Golang"
    var isEnabled bool = false
    fmt.Printf("%T\n", x)         // Output: int
    fmt.Printf("%T\n", y)         // Output: float32
    fmt.Printf("%T\n", z)         // Output: string
    fmt.Printf("%T\n", isEnabled) // Output: bool
}

Output

int
float32
string
bool

Using the interface{}

The interface{} is a special type in Go that can hold any value. For example, when you use the reflect.TypeOf function on a variable with interface{} type, it will return the underlying type of the variable.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var x interface{} = 5
    fmt.Println(reflect.TypeOf(x)) // Output: int
}

Output

int

Conclusion

In conclusion, Go provides multiple ways to determine the type of an object. The reflect.TypeOf function is great for getting the exact type of a variable, including the package path if it's a named type. The %T verb in the fmt.Printf function is useful when you want to get the type of a variable in a formatted string. Finally, the interface{} is a special type in Go that can hold any value, which makes it helpful in checking the underlying type of a variable.

© 2023 W3Basic. All rights reserved.

Follow Us: