且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-03 08:02:52

假设您使用的是流行的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
 }