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

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

How to compare a value in a map with a set of known values

问题

我有一些代码,可以从URL中提取URL参数,并将其放入一个映射中。我可以成功地打印出我想要检查的映射项的值。

  1. values := r.URL.Query()
  2. a := values["a"]
  3. fmt.Println(a)

我注意到当值打印时,它们被包围在"[]"中。

我想要比较每个a、b、c的值,并检查它是否包含在逗号分隔的字符串中。

  1. allowedA := "value1,value2,value3"
  2. if strings.Contains(allowedA, a) {
  3. // 返回true
  4. }

意思是,如果'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.

  1. values := r.URL.Query()
  2. a := values["a"]
  3. 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.

  1. allowedA = "value1,value2,value3"

i.e. something similar to:

  1. 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直接访问参数。

我建议将字符串拆分,并将结果用作映射键,这样您可以将映射用作集合。例如:

  1. allowedAMap := map[string]struct{}{}
  2. allowedAStrs := strings.Split(allowedA, ",")
  3. for _, s := range allowedAStrs {
  4. allowedAMap[s] = struct{}{}
  5. }
  6. //...
  7. if _, ok := allowedAMap[a]; !ok {
  8. fmt.Println("wrong a")
  9. return
  10. }
  11. 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.

  1. allowedAMap := map[string]struct{}{}
  2. allowedAStrs := strings.Split(allowedA, ",")
  3. for _, s := range allowedAStrs {
  4. allowedAMap
    展开收缩
    = struct{}{}
  5. }
  6. //...
  7. if _, ok := allowedAMap[a]; !ok {
  8. fmt.Println("wrong a")
  9. return
  10. }
  11. 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:

确定