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.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算