-1

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

lee.edward01
  • 453
  • 1
  • 6
  • 16
  • The call `mux.Vars(r)` returns a map, `["ID"]` attempts to retrieve a value from the map using the key `"ID"`. Indexing into a map in Go can *optionally* return two values, (1) the one that's mapped to the provided key, (2) a boolean that indicates whether or not a value was actually mapped to the key. – mkopriva Jun 28 '19 at 04:45
  • ... then `!Ok` would trigger when the map does not contain an `ID` key-value. – mkopriva Jun 28 '19 at 04:47

1 Answers1

1

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.

novalagung
  • 10,905
  • 4
  • 58
  • 82