我有一個 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]string
。someMap["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
?}
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消