0

We have a map[string]string, I assume that means the zero value of a string retrieved from the map is ""

So doesn't that mean that this:

var userId, ok = params["user_id"];

if !ok || userId == "" {
    return 422, "Missing user_id in request"
}

is the same logic as this:

var userId = params["user_id"];

if  userId == "" {
    return 422, "Missing user_id in request"
}

just making sure my understanding is correct.

icza
  • 389,944
  • 63
  • 907
  • 827
  • 2
    "is the same logic as this". No, these are not equivalent if `params` contains an empty string "". Otherwise yes. – Volker Feb 24 '20 at 09:45

1 Answers1

4

It's not the same if you intend to store the zero value of the value type.

See this example:

m := map[string]string{
    "empty": "",
}

if v, ok := m["empty"]; ok {
    fmt.Printf("'empty' is present: %q\n", v)
} else {
    fmt.Println("'empty' is not present")
}
if v, ok := m["missing"]; ok {
    fmt.Printf("'missing' is present: %q\n", v)
} else {
    fmt.Printf("'missing' is not present")
}

It outputs (try it on the Go Playground):

'empty' is present: ""
'missing' is not present

It's true that if you never store the zero value in the map, you may simply use if m[value] == zeroValue {}. This is detailed here: How to check if a map contains a key in Go?

This "property" of maps can be exploited to create sets elegantly. See How can I create an array that contains unique strings?

And using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition

icza
  • 389,944
  • 63
  • 907
  • 827