Cookies management by TermsFeed Cookie Consent

πŸ€” Print type of variable in Go

Last updated:
introduction type format

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 the 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 a variable, it is better 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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

πŸ“° String padding in Go

Learn how to print aligned strings padded with spaces
introduction strings format

♾️ Infinite loop in Go

Learn how to define a “while true” loop
introduction loop

πŸ“” Convert a struct to io.Reader in Go

Learn how to convert a struct to io.Reader and send it as an HTTP POST request body
introduction http