Skip to content

Commit 0f06ba2

Browse files
authoredJun 20, 2017
Update go-tips.cn.md
1 parent 26cf7ec commit 0f06ba2

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
 

‎go-tips.cn.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,92 @@ json.Marshal(struct {
3232
})
3333
```
3434

35+
# 临时添加额外的字段
36+
37+
```golang
38+
type User struct {
39+
Email string `json:"email"`
40+
Password string `json:"password"`
41+
// many more fields…
42+
}
43+
```
44+
45+
临时忽略掉Password字段,并且添加token字段
46+
47+
```golang
48+
json.Marshal(struct {
49+
*User
50+
Token string `json:"token"`
51+
Password bool `json:"password,omitempty"`
52+
}{
53+
User: user,
54+
Token: token,
55+
})
56+
```
57+
3558
# 临时粘合两个struct
59+
60+
```golang
61+
type BlogPost struct {
62+
URL string `json:"url"`
63+
Title string `json:"title"`
64+
}
65+
66+
type Analytics struct {
67+
Visitors int `json:"visitors"`
68+
PageViews int `json:"page_views"`
69+
}
70+
71+
json.Marshal(struct{
72+
*BlogPost
73+
*Analytics
74+
}{post, analytics})
75+
```
76+
3677
# 一个json切分成两个struct
78+
79+
```golang
80+
json.Unmarshal([]byte(`{
81+
"url": "attila@attilaolah.eu",
82+
"title": "Attila's Blog",
83+
"visitors": 6,
84+
"page_views": 14
85+
}`), &struct {
86+
*BlogPost
87+
*Analytics
88+
}{&post, &analytics})
89+
```
90+
3791
# 临时改名struct的字段
92+
93+
```golang
94+
type CacheItem struct {
95+
Key string `json:"key"`
96+
MaxAge int `json:"cacheAge"`
97+
Value Value `json:"cacheValue"`
98+
}
99+
100+
json.Marshal(struct{
101+
*CacheItem
102+
103+
// Omit bad keys
104+
OmitMaxAge omit `json:"cacheAge,omitempty"`
105+
OmitValue omit `json:"cacheValue,omitempty"`
106+
107+
// Add nice keys
108+
MaxAge int `json:"max_age"`
109+
Value *Value `json:"value"`
110+
}{
111+
CacheItem: item,
112+
113+
// Set the int by value:
114+
MaxAge: item.MaxAge,
115+
116+
// Set the nested struct by reference, avoid making a copy:
117+
Value: &item.Value,
118+
})
119+
```
120+
38121
# 用字符串传递数字
39122
# 容忍字符串和数字互转
40123
# 容忍空数组作为对象

0 commit comments

Comments
 (0)
Please sign in to comment.