Skip to content

Commit 368a129

Browse files
committed
update reflect
1 parent 03c2013 commit 368a129

File tree

2 files changed

+59
-7
lines changed

2 files changed

+59
-7
lines changed

std/reflect/type_test.go

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package reflect_test
33
import (
44
"fmt"
55
"reflect"
6+
"strings"
67
"testing"
78
)
89

@@ -11,9 +12,17 @@ type I interface {
1112
Write(p []byte) (n int, err error)
1213
}
1314

15+
type Coordinate struct {
16+
long float32
17+
lat float32
18+
}
19+
1420
type User struct {
15-
Name string
16-
age int
21+
ID int
22+
Name string
23+
age int
24+
address []string
25+
Coordinate Coordinate
1726
}
1827

1928
func (u *User) SetAge(age int) *User {
@@ -76,3 +85,35 @@ func TestKind(t *testing.T) {
7685
fmt.Println(reflect.Kind(1))
7786
fmt.Println(reflect.Kind(0.0))
7887
}
88+
89+
type S struct {
90+
A string `json:"a"`
91+
B byte `json:"b"`
92+
C bool `json:"c,omitempty"`
93+
Name string `json:"name"`
94+
}
95+
96+
func (s S) M1() string {
97+
return s.A
98+
}
99+
100+
func TestTag(t *testing.T) {
101+
ts := reflect.TypeOf(*&S{
102+
A: "hello world",
103+
B: 1,
104+
C: false,
105+
Name: "zing",
106+
})
107+
fmt.Println(ts)
108+
109+
fmt.Println(ts.NumField())
110+
fmt.Println(ts.NumMethod())
111+
for i := 0; i < ts.NumField(); i++ {
112+
if value, ok := ts.Field(i).Tag.Lookup("json"); ok {
113+
fmt.Println(value, strings.Split(value, ","), strings.Split(value, ",")[0])
114+
}
115+
fmt.Println("Field.Name: ", ts.Field(i).Name)
116+
fmt.Println("Field.Type: ", ts.Field(i).Type)
117+
}
118+
119+
}

std/reflect/value_test.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,24 @@ func TestValueOfMethods(t *testing.T) {
3333
t.Log("Addr: ", value.Addr())
3434
}
3535

36-
func TestStruct(t *testing.T) {
37-
type User struct {
38-
Id int `json:"id"`
39-
Name string `json:"name"`
36+
func TestGetVal(t *testing.T) {
37+
user := User{ID: 1, Name: "zing", age: 20, address: []string{"无锡", "上海"}, Coordinate: Coordinate{long: 11.11, lat: 12.22}}
38+
v := reflect.ValueOf(user)
39+
fmt.Println(v)
40+
41+
for i := 0; i < v.NumField(); i++ {
42+
f := v.Field(i)
43+
fmt.Println("Kind: ", f.Kind(), " Type: ", f.Type(), " String: ", f.String(), " v: ", f, fmt.Sprintf("v: %v", f))
4044
}
41-
user := &User{Id: 1, Name: "zing"}
45+
}
46+
47+
func TestStruct(t *testing.T) {
48+
user := &User{ID: 1, Name: "zing"}
4249
value := reflect.ValueOf(user)
50+
for i := 0; i < value.NumField(); i++ {
51+
fmt.Println(value.Elem())
52+
}
53+
4354
t.Log(user)
4455
t.Log(value)
4556
t.Log(value.IsValid())

0 commit comments

Comments
 (0)