英文:
How to compare a value in a map with a set of known values
问题
我有一些代码,可以从URL中提取URL参数,并将其放入一个映射中。我可以成功地打印出我想要检查的映射项的值。
values := r.URL.Query()
a := values["a"]
fmt.Println(a)
我注意到当值打印时,它们被包围在"[]"中。
我想要比较每个a、b、c的值,并检查它是否包含在逗号分隔的字符串中。
allowedA := "value1,value2,value3"
if strings.Contains(allowedA, a) {
// 返回true
}
意思是,如果'a'中的值包含在变量'allowedA'中,则返回true。
有什么建议吗?
英文:
I have some code that pulls out the URL parameters from a URL and places it into a map. I can successfully print out the values of the map items that I want to examine.
values := r.URL.Query()
a := values["a"]
fmt.Println(a)
I notice when the values print they print with "[]" surrounding them.
I'd like to value the value of each a,b,c and check to see if it is contained in a comma-delimited string.
allowedA = "value1,value2,value3"
i.e. something similar to:
if(contains(allowedA,a)
Meaning "if the value in 'a' is contained in the variable 'allowedA' then return true.
Any suggestions?
答案1
得分: 1
我注意到当值打印时,它们会用"[]"括起来。
这是因为url.Values
是map[string][]string
,而不是map[string]string
。使用url.Values.Get
直接访问参数。
我建议将字符串拆分,并将结果用作映射键,这样您可以将映射用作集合。例如:
allowedAMap := map[string]struct{}{}
allowedAStrs := strings.Split(allowedA, ",")
for _, s := range allowedAStrs {
allowedAMap[s] = struct{}{}
}
//...
if _, ok := allowedAMap[a]; !ok {
fmt.Println("wrong a")
return
}
fmt.Println("correct a")
英文:
>I notice when the values print they print with "[]" surrounding them.
That's because url.Values
is map[string][]string
, not map[string]string
. Use url.Values.Get
to access the parameter directly.
>I'd like to value the value of each a,b,c and check to see if it is contained in a comma-delimited string.
I'd suggest splitting the string and using the result as map keys, so that you could use the map as a set. I.e.
allowedAMap := map[string]struct{}{}
allowedAStrs := strings.Split(allowedA, ",")
for _, s := range allowedAStrs {
allowedAMap展开收缩 = struct{}{}
}
//...
if _, ok := allowedAMap[a]; !ok {
fmt.Println("wrong a")
return
}
fmt.Println("correct a")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论