如何安全地加载哈希,并将值转换为布尔值(如果存在) [英] How to safely load a hash, and convert a value to a boolean if it exists

查看:65
本文介绍了如何安全地加载哈希,并将值转换为布尔值(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个redis哈希,它具有要转换为布尔值的键"has_ended".

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"]

如果键"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?

推荐答案

假设您使用的是流行的github.com/go-redis/redis包,则 HGetAll(key).Result()的返回值 map [string] string (的值为空字符串.

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.

当且仅当键的值为"true"时,hasEnded为true时,请使用以下命令:

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"

使用 strconv.ParseBool 处理更大范围的可能值(1,t,T,TRUE,true,True,0,f,F,FALSE,false,False):

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
 }

这篇关于如何安全地加载哈希,并将值转换为布尔值(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆