dongzhou4727 2017-10-23 17:49
浏览 318
已采纳

在Redigo中将布尔值扫描为“ false”和“ true”

How can I use redis.ScanStruct to parse strings as booleans or even as custom types?

The struct I am using looks like this:

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

The RequireSecret attribute is either a "true" or "false" string, I'd like to scan it as a bool.

  • 写回答

1条回答 默认 最新

  • douchun6221 2017-10-23 18:52
    关注

    To scan the result of HGETALL, use the following type

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

    with the following command:

    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
    }
    

    Because Redigo uses strconv.ParseBool to convert Redis result values to bool, you don't need to implement the scanner interface to convert "true" and "false" to true and false.

    You can implement the scanner interface on a subset of a struct's fields. Redigo will use the default parsing for fields that do not implement the interface and the application's custom parser for the fields that do implement the interface.

    Unless you need to access individual hash elements through the Redis API, it's usually better store sructs as a Redis string by serializing the struct using JSON, gob or some other encoder.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机