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

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

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错