drnl10253 2018-11-01 00:39
浏览 102
已采纳

如何安全地加载哈希,并将值转换为布尔值(如果存在)

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条回答 默认 最新

  • douque9815 2018-11-01 01:10
    关注

    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
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!