1
votes

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

1 Answers

1
votes

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