go - 在 Redigo 中将 "false"和 "true"扫描为 bool 值

标签 go redis redigo

如何使用 redis.ScanStruct 将字符串解析为 bool 值甚至自定义类型?

我使用的结构如下所示:

type Attrs struct {
    Secret         string `redis:"secret"`
    RequireSecret  string `redis:"requireSecret"`
    UserID         string `redis:"userId"`
}

RequireSecret 属性是“true”或“false”字符串,我想将其扫描为 bool

最佳答案

要扫描 HGETALL 的结果,请使用以下类型

type Attrs struct {
    Secret         string `redis:"secret"`
    RequireSecret  bool `redis:"requireSecret"`
    UserID         string `redis:"userId"`
}

使用以下命令:

values, err := redis.Values(c.Do("HGETALL", key))
if err != nil {
   // handle error
}
var attrs Attrs
err = redis.ScanStruct(values, &attrs)
if err != nil {
   // handle error
}

因为 Redigo 使用 strconv.ParseBool要将 Redis 结果值转换为 bool,您不需要实现扫描器接口(interface)来将 "true""false" 转换为 truefalse

您可以在结构字段的子集上实现扫描器接口(interface)。 Redigo 将为未实现接口(interface)的字段使用默认解析器,并为实现接口(interface)的字段使用应用程序的自定义解析器。

除非您需要通过 Redis API 访问单个哈希元素,否则通常最好通过使用 JSON、gob 或其他编码器序列化结构将结构存储为 Redis 字符串。

关于go - 在 Redigo 中将 "false"和 "true"扫描为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46895530/

相关文章:

python - 在 Celery 任务中使用 Redis 连接和保存数据

json - 无法将字符串映射转换为 json

go - json.Marshal用于带有回显的http发布请求

go - 云功能e2e

lua - Redis 集群 : Find which master holds particular key/slot

amazon-web-services - Redis集群在不同主机上有什么好处?

python - Redis 使用的 RAM 不足

go - 如何在 redisearch-go (Golang) 中向 redigo 客户端提供密码

go - 将 curl 命令转换为 golang 函数

dictionary - 当键不在 map 中时不引发错误(如 Python)有什么好处?