douying9296 2018-08-17 14:52
浏览 386
已采纳

Redigo ScanStruct错误与time.Time

I am trying to read a struct that has a field of type time.Time using redigo's ScanStruct, which gives me the following error: cannot convert from Redis bulk string to time.Time.

Is the only way of fixing this to create my own time type that extends time.Time and implements RedisScan? That sounds bad as well...

  • 写回答

1条回答 默认 最新

  • dongyuanguang3893 2018-08-17 20:09
    关注

    Since Redis has no concept of time values it would make no sense for a generic driver such as redigo to perform some automatic conversion between the builin time.Time type and an arbitrary byte array. As such, it's up to the programmer to decide how to perform that conversion.

    For example, supposing you have a "Person" type defined as such, including a created_at timestamp formatted as RFC3339 (a form of ISO 8601), you could define a custom "Timestamp" type with a "RedisScan" method as follows:

    type Timestamp time.Time
    
    type Person struct {
      Id        int       `redis:"id"`
      Name      string    `redis:"name"`
      CreatedAt Timestamp `redis:"created_at"`
    }
    
    func (t *Timestamp) RedisScan(x interface{}) error {
      bs, ok := x.([]byte)
      if !ok {
        return fmt.Errorf("expected []byte, got %T", x)
      }
      tt, err := time.Parse(time.RFC3339, string(bs))
      if err != nil {
        return err
      }
      *t = Timestamp(tt)
      return nil
    }
    
    // ...
    
    response, err := redis.Values(conn.Do("HGETALL", "person:1"))
    if err != nil {
      panic(err)
    }
    
    var p Person
    err = redis.ScanStruct(response, &p)
    if err != nil {
      panic(err)
    }
    log.Printf("OK: p=%v", p)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?