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