forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples_test.go
84 lines (75 loc) · 1.66 KB
/
examples_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package structs_test
import (
"fmt"
"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/structs"
)
func ExampleToMap() {
type Extra struct {
City string `json:"city"`
Github string `json:"github"`
}
type User struct {
Name string `json:"name"`
Age int `json:"age"`
Extra Extra `json:"extra"`
}
u := &User{
Name: "inhere",
Age: 30,
Extra: Extra{
City: "chengdu",
Github: "https://github.com/inhere",
},
}
mp := structs.ToMap(u)
dump.P(mp)
/*dump:
map[string]interface {} { #len=3
"name": string("inhere"), #len=6
"age": int(30),
"extra": map[string]interface {} { #len=2
"city": string("chengdu"), #len=7
"github": string("https://github.com/inhere"), #len=25
},
},
*/
fmt.Println("mp.ame:", mp["name"])
fmt.Println("mp.age:", mp["age"])
// Output:
// mp.ame: inhere
// mp.age: 30
}
func ExampleInitDefaults() {
type Extra struct {
City string `default:"chengdu"`
Github string `default:"https://github.com/inhere"`
}
type User struct {
Name string `default:"inhere"`
Age int `default:"30"`
Extra Extra `default:""` // add tag for init sub struct
}
u := &User{}
_ = structs.InitDefaults(u)
dump.P(u)
/*dump:
&structs_test.User {
Name: string("inhere"), #len=6
Age: int(30),
Extra: structs_test.Extra {
City: string("chengdu"), #len=7
Github: string("https://github.com/inhere"), #len=25
},
},
*/
fmt.Println("Name:", u.Name)
fmt.Println("Age:", u.Age)
fmt.Println("Extra.City:", u.Extra.City)
fmt.Println("Extra.Github:", u.Extra.Github)
// Output:
// Name: inhere
// Age: 30
// Extra.City: chengdu
// Extra.Github: https://github.com/inhere
}