gpt4 book ai didi

go - 通过将键与字符串数组进行比较来从 map 中检索

转载 作者:IT王子 更新时间:2023-10-29 02:09:54 26 4
gpt4 key购买 nike

我有一些返回值映射的 Go 代码,但我只需要一些结果。有没有一种方法可以针对字符串数组(或类似的东西)测试/过滤 map 的键以提供简化的结果而不是一堆 if 语句?我查找的所有样本都有固定值来过滤。

下面是一个简单的例子,但我不想提供字符串,而是想要一个可能值的列表,这样我就可以得到一个简化的列表。

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)
}

最佳答案

是的,您可以使用 range 测试/过滤 map 。如果您拥有所有可能的值,则可以使用键/值查找将它们与 map 进行简单比较,并以此为基础制作结构。

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

关于go - 通过将键与字符串数组进行比较来从 map 中检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49929846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com