如何将地图中的一个值与一组已知值进行比较

huangapple go评论78阅读模式
英文:

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.Valuesmap[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")

huangapple
  • 本文由 发表于 2015年10月23日 20:01:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/33301847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定