转到:分配给嵌套结构

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())
}

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.