Golang

获取变量的数据类型

 1package main
 2
 3import (
 4	"fmt"
 5	"reflect"
 6)
 7
 8func main() {
 9
10	// string type : string
11	var1 := "hello world"
12
13	// integer : int
14	var2 := 10
15
16	// float : float64
17	var3 := 1.55
18
19	// boolean : bool
20	var4 := true
21
22	// shorthand string array declaration : []string
23	var5 := []string{"foo", "bar", "baz"}
24
25	// map is reference datatype : map[string]string
26	var6 := map[int]string{100: "Ana", 101: "Lisa", 102: "Rob"}
27
28	// complex64 and complex128
29	// is basic datatype : complex128
30	var7 := complex(9, 15)
31
32	// using %T format specifier to
33	// determine the datatype of the variables
34
35	fmt.Println("Using Percent T with Printf")
36
37	fmt.Printf("var1 = %T\n", var1)
38	fmt.Printf("var2 = %T\n", var2)
39	fmt.Printf("var3 = %T\n", var3)
40	fmt.Printf("var4 = %T\n", var4)
41	fmt.Printf("var5 = %T\n", var5)
42	fmt.Printf("var6 = %T\n", var6)
43	fmt.Printf("var7 = %T\n", var7)
44
45	// using TypeOf() method of reflect package
46	// to determine the datatype of the variables
47	fmt.Println()
48	fmt.Println("Using reflect.TypeOf Function")
49
50	fmt.Println("var1 = ", reflect.TypeOf(var1))
51	fmt.Println("var2 = ", reflect.TypeOf(var2))
52	fmt.Println("var3 = ", reflect.TypeOf(var3))
53	fmt.Println("var4 = ", reflect.TypeOf(var4))
54	fmt.Println("var5 = ", reflect.TypeOf(var5))
55	fmt.Println("var6 = ", reflect.TypeOf(var6))
56	fmt.Println("var7 = ", reflect.TypeOf(var7))
57
58	// using ValueOf() method of reflect package
59	// to determine the value of the variable
60	// Kind() method returns the datatype of the
61	// value fetched by the ValueOf() method
62	fmt.Println()
63	fmt.Println("Using reflect.ValueOf.Kind() Function")
64
65	fmt.Println("var1 = ", reflect.ValueOf(var1).Kind())
66	fmt.Println("var2 = ", reflect.ValueOf(var2).Kind())
67	fmt.Println("var3 = ", reflect.ValueOf(var3).Kind())
68	fmt.Println("var4 = ", reflect.ValueOf(var4).Kind())
69	fmt.Println("var5 = ", reflect.ValueOf(var5).Kind())
70	fmt.Println("var6 = ", reflect.ValueOf(var6).Kind())
71	fmt.Println("var7 = ", reflect.ValueOf(var7).Kind())
72
73}

image-20210316005442799