douhao9203 2015-10-23 12:01
浏览 27

如何将映射中的值与一组已知值进行比较

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条回答 默认 最新

  • dongyou6795 2015-10-23 12:12
    关注

    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[s] = struct{}{}
    }
    //...
    if _, ok := allowedAMap[a]; !ok {
        fmt.Println("wrong a")
        return
    }
    fmt.Println("correct a")
    
    评论

报告相同问题?

悬赏问题

  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能