回答

收藏

如何在golang切片中搜索元素

技术问答 技术问答 277 人阅读 | 0 人回复 | 2023-09-12

我有结构体。/ d0 H- N# k1 u$ x, t6 e
    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
这是输出:3 {* W; I1 o, ]# m& }
    [{key1 test} {web/key1 test2}]
    " Z, N5 `" k8 A/ y0 C( F9 p
如何搜索这个数组获取元素 where key="key1"?6 m& g- G) H9 u, t, r
                                                               
* t9 x" P5 W, w+ M" F    解决方案:                                                                  H8 Z3 i( Y; z8 F, e# @
                                                                用简单的for循环:' R* W- T) [6 C% j% `
      W2 Q5 C7 ?! a8 g7 x
  • 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. _
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则