...
Source file
src/reflect/example_test.go
Documentation: reflect
1
2
3
4
5 package reflect_test
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "io"
12 "os"
13 "reflect"
14 )
15
16 func ExampleMakeFunc() {
17
18
19
20
21 swap := func(in []reflect.Value) []reflect.Value {
22 return []reflect.Value{in[1], in[0]}
23 }
24
25
26
27
28
29
30 makeSwap := func(fptr interface{}) {
31
32
33
34 fn := reflect.ValueOf(fptr).Elem()
35
36
37 v := reflect.MakeFunc(fn.Type(), swap)
38
39
40 fn.Set(v)
41 }
42
43
44 var intSwap func(int, int) (int, int)
45 makeSwap(&intSwap)
46 fmt.Println(intSwap(0, 1))
47
48
49 var floatSwap func(float64, float64) (float64, float64)
50 makeSwap(&floatSwap)
51 fmt.Println(floatSwap(2.72, 3.14))
52
53
54
55
56 }
57
58 func ExampleStructTag() {
59 type S struct {
60 F string `species:"gopher" color:"blue"`
61 }
62
63 s := S{}
64 st := reflect.TypeOf(s)
65 field := st.Field(0)
66 fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
67
68
69
70 }
71
72 func ExampleStructTag_Lookup() {
73 type S struct {
74 F0 string `alias:"field_0"`
75 F1 string `alias:""`
76 F2 string
77 }
78
79 s := S{}
80 st := reflect.TypeOf(s)
81 for i := 0; i < st.NumField(); i++ {
82 field := st.Field(i)
83 if alias, ok := field.Tag.Lookup("alias"); ok {
84 if alias == "" {
85 fmt.Println("(blank)")
86 } else {
87 fmt.Println(alias)
88 }
89 } else {
90 fmt.Println("(not specified)")
91 }
92 }
93
94
95
96
97
98 }
99
100 func ExampleTypeOf() {
101
102
103
104 writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
105
106 fileType := reflect.TypeOf((*os.File)(nil))
107 fmt.Println(fileType.Implements(writerType))
108
109
110
111 }
112
113 func ExampleStructOf() {
114 typ := reflect.StructOf([]reflect.StructField{
115 {
116 Name: "Height",
117 Type: reflect.TypeOf(float64(0)),
118 Tag: `json:"height"`,
119 },
120 {
121 Name: "Age",
122 Type: reflect.TypeOf(int(0)),
123 Tag: `json:"age"`,
124 },
125 })
126
127 v := reflect.New(typ).Elem()
128 v.Field(0).SetFloat(0.4)
129 v.Field(1).SetInt(2)
130 s := v.Addr().Interface()
131
132 w := new(bytes.Buffer)
133 if err := json.NewEncoder(w).Encode(s); err != nil {
134 panic(err)
135 }
136
137 fmt.Printf("value: %+v\n", s)
138 fmt.Printf("json: %s", w.Bytes())
139
140 r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))
141 if err := json.NewDecoder(r).Decode(s); err != nil {
142 panic(err)
143 }
144 fmt.Printf("value: %+v\n", s)
145
146
147
148
149
150 }
151
View as plain text