# Determine the Type of a Variable in Go at Runtime

> Use fmt.Printf with the %T verb to print a variable's type, type switches for control flow, or the reflect package for deeper type inspection in Go

**URL:** https://sentry.io/answers/finding-the-type-of-a-variable-in-go/

---

## The Problem

I don't know how to identify the type of a variable in Go.

## The Solution

You can use either the `%T` verb from the [`fmt`](https://pkg.go.dev/fmt) package or the Go [type switches](https://go.dev/ref/spec#Type_switches) to determine variable types in Go.

For the purposes of print debugging, you can get the string representation of a variable using the [`fmt`](https://pkg.go.dev/fmt) package with the `%T` verb:

```go
package main

import "fmt"

func main() {
	example := "some string"
	fmt.Printf("variable's type is: %T", example)
}
```

This prints:

```
variable's type is: string
```

However, if you need to identify the type of a variable for a specific purpose, it is best to use a type switch. Type switches are similar to normal `switch` statements, only they switch types rather than values:

```go
package main

import "fmt"

func main() {
	printType("example") // Prints "received a string".
	printType(42)        // Prints "received an int".
	printType(4.2)       // Prints "received an unknown type".
}

func printType(value any) {
	switch value.(type) {
	case int:
		fmt.Println("received an int")
	case string:
		fmt.Println("received a string")
	default:
		fmt.Println("received an unknown type")
	}
}
```

The [`reflect`](https://pkg.go.dev/reflect) package can also be used to inspect the type information of a variable more deeply:

```go
package main

import (
	"fmt"
	"reflect"
)

func main() {
	example := 42

	reflectType := reflect.TypeOf(example)

	fmt.Printf("example type bits: %d, size (in bytes): %d, string representation: %s", reflectType.Bits(), reflectType.Size(), reflectType.String())
}
```

This prints:

```
example type bits: 64, size (in bytes): 8, string representation: int
```

While the [`reflect`](https://pkg.go.dev/reflect) package is interesting and contains detailed information about the types in your program, it is not performant and you should avoid using it in production environments when possible.

### Further reading

- The [Go `reflect` package](https://pkg.go.dev/reflect)
- [The Laws of Reflection](https://go.dev/blog/laws-of-reflection) blog post

---

*Source: [sentry.io/answers/finding-the-type-of-a-variable-in-go/](https://sentry.io/answers/finding-the-type-of-a-variable-in-go/)*
