To print a variable’s sort, you should utilize the %T
verb within the fmt.Printf()
operate format. It’s the only and most beneficial manner of printing sort of a variable.
bundle important
import (
"fmt"
)
func important() {
t1 := "textual content"
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: %Tn", t1)
fmt.Printf("t2: %Tn", t2)
fmt.Printf("t3: %Tn", t3)
fmt.Printf("t4: %Tn", t4)
fmt.Printf("t5: %Tn", t5)
fmt.Printf("t6: %Tn", t6)
}
Alternatively, you should utilize the TypeOf()
operate from the reflection bundle replicate
. Nonetheless, it makes use of advanced and costly runtime reflection, so when you simply have to print the kind of a variable, it’s higher to make use of the primary technique.
bundle important
import (
"fmt"
"replicate"
)
func important() {
t1 := "textual content"
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: %sn", replicate.TypeOf(t1))
fmt.Printf("t2: %sn", replicate.TypeOf(t2))
fmt.Printf("t3: %sn", replicate.TypeOf(t3))
fmt.Printf("t4: %sn", replicate.TypeOf(t4))
fmt.Printf("t5: %sn", replicate.TypeOf(t5))
fmt.Printf("t6: %sn", replicate.TypeOf(t6))
}
Each strategies return the identical output:
t1: string
t2: []string
t3: map[string]float64
t4: int
t5: float64
t6: bool