dongyao2129 2019-06-28 02:54
浏览 701
已采纳

GoLang / Mux语法问题:如果ID,确定= mux.Vars(r)[“ ID”]; !好

I am very new to Golang and I am reading someone's code for an API using gorilla/mux and I came across this block of code.

func heroGet(w http.ResponseWriter, r *http.Request) {
    var ID string
    var Ok bool
    if ID, Ok = mux.Vars(r)["ID"]; !Ok{
        //do something
    }

I am having trouble understanding what Ok does in this specific situation and when !Ok would trigger.

Note that this function is GET endpoint.

(r.HandleFunc("/hero/{ID}", heroGet).Methods("GET"))

  • 写回答

1条回答 默认 最新

  • dsyua2828 2019-06-28 05:59
    关注

    I assume you are using goriila mux. I checked on the source code, the mux.Vars() returns a value with type is map[string]string.

    In a nutshell, a map datatype can optionally return two values.

    1. The first one is the actual value as per requested key
    2. The second one is an indicator whether item with requested key is exist or not (a boolean value).

    Please take a look at example below:

    vars := map[string]string{
        "one": "1",
        "two": "",
    }
    
    value1, ok1 := vars["one"]
    fmt.Println("value:", value1, "is exists:", ok1)
    // value: 1 is exists: true
    
    value2, ok2 := vars["two"]
    fmt.Println("value:", value2, "is exists:", ok2)
    // value:  is exists: true
    
    value3, ok3 := vars["three"]
    fmt.Println("value:", value3, "is exists:", ok3)
    // value:  is exists: false
    

    From example above we can clearly see, if requested item does not exists, then the 2nd return will be false.

    If the item is exists even though the value is zero value, then 2nd return will still be true, because the item is indeed exist, doesn't necessarily important what the value is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条