🤔 Print type of variable in Golang

introduction type

To print a variable’s type, you can use the %T verb in the fmt.Printf function format. It’s the simplest and most recommended way of printing type of a variable.

package main

import (
    "fmt"
)

func main() {
    t1 := "text"
    t2 := []string{"apple", "strawberry", "blueberry"}
    t3 := map[string]float64{"strawberry": 3.2, "blueberry": 1.2}
    t4 := 2
    t5 := 4.5
    t6 := true

    fmt.Printf("t1: %T\n", t1)
    fmt.Printf("t2: %T\n", t2)
    fmt.Printf("t3: %T\n", t3)
    fmt.Printf("t4: %T\n", t4)
    fmt.Printf("t5: %T\n", t5)
    fmt.Printf("t6: %T\n", t6)
}

Alternatively, you can use TypeOf function from the reflection package reflect. However, it uses complex and expensive runtime reflection, so if you just need to print the type of variable, it’s a better idea to use the first method.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    t1 := "text"
    t2 := []string{"apple", "strawberry", "blueberry"}
    t3 := map[string]float64{"strawberry": 3.2, "blueberry": 1.2}
    t4 := 2
    t5 := 4.5
    t6 := true

    fmt.Printf("t1: %s\n", reflect.TypeOf(t1))
    fmt.Printf("t2: %s\n", reflect.TypeOf(t2))
    fmt.Printf("t3: %s\n", reflect.TypeOf(t3))
    fmt.Printf("t4: %s\n", reflect.TypeOf(t4))
    fmt.Printf("t5: %s\n", reflect.TypeOf(t5))
    fmt.Printf("t6: %s\n", reflect.TypeOf(t6))
}

Both methods return the same output:

t1: string
t2: []string
t3: map[string]float64
t4: int
t5: float64
t6: bool

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice

🏟️ Capacity and length of a slice in Go

Learn what is the difference between length and capacity of a slice
introduction slice array