dongpaipu8394 2012-11-16 10:18
浏览 35
已采纳

复合类型和指针方法

i have some problems creating a own type Date based on type time.Time

i tried to create the Date type as follows:

type Date time.Time

func (d Date) UnmarshalJSON(buf []byte) error {
    var s string
    json.Unmarshal(buf, &s)
    t, err := time.Parse(timeLayout,s)
    d= Date(t)
    return err
}

func (d Date) MarshalJSON() ([]byte, error) {
    b,_ := json.Marshal(d.Format(timeLayout))
    return b,nil
}

this itself works, i can store this Date as a time.Time in AppEngine Datastore. the marshaling itself also works, but is not working is: then when unmarshal from json, the Date d is filled with the value. this is, as i understand right, because the unmarshalJson function create a copy of Date.

so when i change the unmarshalJson function to use a Pointer to Date then i cant use:

d=Date(t)

so first question, is there a solution how todo this ?

what i have done now is to rewrite the Code as follows:

type Date struct {
    t time.Time
}

func (d *Date) UnmarshalJSON(buf []byte) error {
    var s string
    json.Unmarshal(buf, &s)
    t, err := time.Parse(timeLayout,s)
    d.t = t
    return err
}

func (d Date) MarshalJSON() ([]byte, error) {
    b,_ := json.Marshal(d.t.Format(timeLayout))
    return b,nil
}

this works, but in this case Date is not an extending type of time.Time its just a wrapper to a time.Time type.

is there a better solution todo this ? im still new to go.

i need this Date type, to have a Date only json formated type, because Chrome only supports the html5 type: date and not datetime. and method overriding is not possible in go (means to override the un/marshalJson methods of type time.Time ) ?

thanks

  • 写回答

1条回答 默认 最新

  • douhuangjie4503 2012-11-16 10:38
    关注

    Totally untested code:

    type Date time.Time
    
    func (d *Date) UnmarshalJSON(buf []byte) error {
            var s string
            json.Unmarshal(buf, &s)
            t, err := time.Parse(timeLayout, s)
            *d = *(*Date)(&t)
            return err
    }
    
    func (d *Date) MarshalJSON() ([]byte, error) {
            b, _ := json.Marshal(d.Format(timeLayout))
            return b, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波