dppxp79175 2016-02-04 20:50
浏览 56
已采纳

创建自定义类型,当检查Golang类型时,它看起来会像另一个类型

I am a experienced python programmer but I am still new to Golang so my apologies if this is an obvious or silly question. But I am trying to create my own type that I want to act exactly like the base type with the exception of several methods being overridden. The reason for this is because several libraries I am using are checking the type against time.Time and I want it to match.

type PythonTime struct {
    time.Time
}

var pythonTimeFormatStr = "2006-01-02 15:04:05-0700"

func (self *PythonTime) UnmarshalJSON(b []byte) (err error) {
    // removes prepending/trailing " in the string
    if b[0] == '"' && b[len(b)-1] == '"' {
        b = b[1 : len(b)-1]
    }
    self.Time, err = time.Parse(pythonTimeFormatStr, string(b))
    return
}

func (self *PythonTime) MarshalJSON() ([]byte, error) {
    return []byte(self.Time.Format(pythonTimeFormatStr)), nil
}

type OtherType struct {
    Uuid     string     `json:"uuid`
    Second   PythonTime `json:"second"`
    Location string     `json:"location"`
    Action   string     `json:"action"`
    Duration int        `json:"duration"`
    Value    string     `json:"value"`
}

So the the above works fine for marshalling and unmarshalling JSON. However, for my library that I am using (gocql and cqlr) they are checking if the type is a time.Time type so they can make some other modifications before putting it in C*. How do I get my PythonTime type to equate to either show as time.Time or override the default marshalling/unmarshalling for a time.Time object just for the use of my OtherType objects?

My temporary solution has been to modify their code and add a special case for the PythonTime type that does the same thing as the time.Time type. However, this is causing me circular imports and is not the best solution. Here is their code with my modifications.

func marshalTimestamp(info TypeInfo, value interface{}) ([]byte, error) {
    switch v := value.(type) {
    case Marshaler:
        return v.MarshalCQL(info)
    case int64:
        return encBigInt(v), nil
    case time.Time:
        if v.IsZero() {
            return []byte{}, nil
        }
        x := int64(v.UTC().Unix()*1e3) + int64(v.UTC().Nanosecond()/1e6)
        return encBigInt(x), nil
    case models.PythonTime:
        x := int64(v.UTC().Unix()*1e3) + int64(v.UTC().Nanosecond()/1e6)
        return encBigInt(x), nil
    }

    if value == nil {
        return nil, nil
    }

    rv := reflect.ValueOf(value)
    switch rv.Type().Kind() {
    case reflect.Int64:
        return encBigInt(rv.Int()), nil
    }
    return nil, marshalErrorf("can not marshal %T into %s", value, info)
}
  • 写回答

3条回答 默认 最新

  • douliang4858 2016-02-05 15:45
    关注

    Just like you have done with the json.Marshaler and json.Unamrshaler, you can also implement the gocql.Marshaler gocql.Unamrshaler interfaces.

    func (t *PythonTime) MarshalCQL(info gocql.TypeInfo) ([]byte, error) {
        b := make([]byte, 8)
        x := t.UnixNano() / int64(time.Millisecond)
        binary.BigEndian.PutUint64(b, uint64(x))
        return b, nil
    }
    
    func (t *PythonTime) UnmarshalCQL(info gocql.TypeInfo, data []byte) error {
        x := int64(binary.BigEndian.Uint64(data)) * int64(time.Millisecond)
        t.Time = time.Unix(0, x)
        return nil
    }
    

    (note, untested in the context of CQL, but this does round-trip with itself)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算