How to safely load a hash, and convert a value to a boolean if it exists

醉酒当歌 提交于 2021-01-29 08:02:28

问题


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?


回答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
 }


来源:https://stackoverflow.com/questions/53093748/how-to-safely-load-a-hash-and-convert-a-value-to-a-boolean-if-it-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!