type Config struct Key string Value string}// I form a slice of the above structvar myconfig []Config // unmarshal a response body into the above sliceif err := json.Unmarshal(respbody,&myconfig); err != nil panic(err)}fmt.Println(config) 1 ~) f2 N+ X/ f1 w
for _,v := range myconfig if v.Key == "key1" // Found! code]请注意,因为切片的元素类型是 a struct(不是指针),如果结构类型大 ; z/ c; r: t) X- y F
range只在索引上使用循环更快,以避免复制元素: " u# O9 ?0 {" t9 U
[code]for i := range myconfig if myconfig.Key == "key1" // Found! code]笔记: 6 f' O4 D, c) t% f: m4 L
这取决于你的情况,多个配置是否可能相同key,但如果没有,break如果找到匹配项,应退出循环(避免搜索其他配置)。 ( W+ {; \5 P& `. k: V
[code]for i := range myconfig if myconfig.Key == "key1" // Found! break code]另外,如果这是一个频繁的操作,你应该考虑map构建一个你可以简单索引的,比如[code]// Build a config map:confMap := map[string]string{}for _,v := range myconfig confMap[v.Key] = v.Value}// And then to find values by key:if v,ok := confMap["key1"]; ok // Found}" b, X- K0 v# ]4 `3 S. _