0

I have a redis hash that has a key "has_ended" that I want to convert to a boolean value.

someMap, _ := rv.redis.HGetAll(key).Result() // returns map[string]interface{}

hasEnded := someMap["has_ended"]

If the key "has_ended" isn't present in the map and I try to convert it to a boolean it will crash. How can I write this safely?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • You can use the second return value to determine if the key exists in the map i.e. `hasEnded, exists := someMap["has_ended"]`. When doing the type assertion, you can do the same thing to determine if the assertion happened without error i.e. `b, ok := hasEnded.(bool)`. – Gavin Nov 01 '18 at 00:43

1 Answers1

1

Assuming that you are using the popular github.com/go-redis/redis package, the return value from HGetAll(key).Result() is a map[string]string (doc). The expression someMap["has_ended"] evaluates to the empty string if the key is not present.

If hasEnded is true if and only if the key is present with the value "true", then use the following:

 hasEnded := someMap["has_ended"] == "true"

Use strconv.ParseBool to a handle a wider range of possible values (1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False):

 hasEnded, err := strconv.ParseBool(someMap["has_ended"])
 if err != nil {
     // handle invalid value or missing value, possibly by setting hasEnded to false
 }
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242