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 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)