dovt85093 2018-04-19 20:38
浏览 9
已采纳

通过将键与字符串数组进行比较来从映射中检索

I have some Go code that is returning a map of values but I only need some of the results. Is there a way I can test/filter the key of the map against a string array (or something similar) to give a simplified result rather than a bunch of if statements? All the samples I have looked up had fixed values to filter against.

A simple example is below, but rather than supplying the string I want to have a list of possible values so I can get a reduced list.

package main

import "fmt"

type colors struct {
    animal  string
    COLOR   []string
}

func main() {
    // Map animal names to color strings.
    colors := map[string]string{
        "bird":  "blue",
        "snake": "green",
        "cat":   "black",
    }

    // Display string.
    fmt.Println(colors)
}
  • 写回答

1条回答 默认 最新

  • dongtaoxue4674 2018-04-19 21:00
    关注

    Yes, you can test/filter a map using range. If you have all the possible values, you can simply compare them to the map using a key/value lookup and make the structs based off of that.

    package main
    
    import (
        "fmt"
    )
    
    
    type colors struct {
    animal  string
    COLOR   []string
    }
    
    func main() {
        //the list of values
        possibleValues := []string{"bird","dog", "cat"}
        // Map animal names to color strings.
    
        foo := map[string]string{
            "bird":  "blue",
                "snake": "green",
                "cat":   "black",
            }
    
        //slice of objects of your struct
        objects := []colors{}
        //for every value in the possible values
        for _, v := range possibleValues {
            //if it's in the map, make a new struct and append it to the slice of objects
            if val,ok := foo[v]; ok {
                objects = append(objects, colors{animal:v,COLOR:[]string{val}})
            }
        }
        // Display string.
        fmt.Println(objects)
    
    }
    

    https://play.golang.org/p/njD6E_WssHT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况