回答

收藏

如何在golang切片中搜索元素

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

我有结构体。, ?* ^) @" E3 X9 G- R) j
    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 |. U1 H1 Q$ n$ u+ {% S: i
这是输出:4 \4 ~+ d- R; \( V1 g4 p
    [{key1 test} {web/key1 test2}]
    # I2 y( `* V/ t
如何搜索这个数组获取元素 where key="key1"?
$ ^0 L3 e1 {3 P) I9 z) u                                                                ' e% v8 d/ t3 R& r) T
    解决方案:                                                               
  O6 s5 D$ n4 A- ^6 ~+ G$ H                                                                用简单的for循环:
4 o7 t/ t! k" {6 c3 W5 ^$ x+ {
    4 X% v/ b0 L4 H- E# ^0 Y
  • for _,v := range myconfig    if v.Key == "key1"        // Found!  code]请注意,因为切片的元素类型是 a struct(不是指针),如果结构类型大
    4 e# o/ p9 m6 o
  • range只在索引上使用循环更快,以避免复制元素:
    $ G" U# d# E; r; H5 y6 k! F
  • [code]for i := range myconfig    if myconfig.Key == "key1"        // Found!  code]笔记:& |7 ^0 Q  `$ r# z
  • 这取决于你的情况,多个配置是否可能相同key,但如果没有,break如果找到匹配项,应退出循环(避免搜索其他配置)。
    : \9 F; E# x0 ~- m- n
  • [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}
    ( P" _# @3 N. ^" B- i' S
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则