为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
当年话下 2023-05-04 17:29:50
我有一个 redis 散列,它有一个键“has_ended”,我想将其转换为布尔值。someMap, _ := rv.redis.HGetAll(key).Result() // returns map[string]interface{}hasEnded := someMap["has_ended"]如果地图中不存在键“has_ended”并且我尝试将其转换为布尔值,它将崩溃。我怎样才能安全地写这个?
查看完整描述

1 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

假设您使用的是流行的 github.com/go-redis/redis 包,则返回值HGetAll(key).Result()map[string]stringsomeMap["has_ended"]如果键不存在,表达式的计算结果为空字符串。

如果 hasEnded 为 true 当且仅当键存在且值为“true”时,然后使用以下内容:

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

使用strconv.ParseBool来处理更广泛的可能值(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

 }


查看完整回答
反对 回复 2023-05-04
  • 1 回答
  • 0 关注
  • 66 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信