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