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

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路