doukuiqian5345 2016-09-12 03:02
浏览 27

转到:分配给嵌套结构

Below is a code snippet - I am confused as to how to assign to variables within my nested struct ("myTime") which I am using for JSON decoding. (I have some Unix timestamps in a JSON file and am hoping to learn how to decode them.)

This throws the following error:

main.go:15: cannot use time.Unix(a, 0) (type time.Time) as type *myTime in assignment
main.go:25: t.String undefined (type myTime has no field or method String)

I'm not sure exactly how to go about understanding the issue, so any explanation or a pointer to specific documentation would help greatly!

package main

import (
    "encoding/binary"
    "encoding/json"
    "fmt"
    "log"
    "time"
)

type myTime time.Time

func (t *myTime) UnmarshalJSON(buf []byte) error {
    a, _ := binary.Varint(buf)
    t = time.Unix(a, 0)
    return nil
}

func main() {
    var t myTime

    if err := json.Unmarshal([]byte("123123123.123123"), &t); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("result: %f
", t.String())
}
  • 写回答

1条回答 默认 最新

  • dongmeng1402 2016-09-12 03:11
    关注

    time.Unix returns a time.Time value (not pointer)

    so just do *t = myTime(time.Unix(a,0))

    This basically assigns the value returned from time.Unix(a,0) to the value pointed to by t

    as for String, you have to make your own:

    func (m myTime) String() string { return time.Time(m).String() }

    This is because when you alias a type, you do not inherit its method set. so you must declare any method you want yourself.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度