为什么map [time.Time]字符串有时不起作用?

This is an example to show when map[time.Time]string "doesn't work".

package main

import (
    "fmt"
    "time"
)

type MyDate time.Time

func NewMyDate(year, month, day int, tz time.Location) (MyDate, error) {
    return MyDate(time.Date(year, time.Month(month), day, 0, 0, 0, 0, &tz)), nil
}

func (md MyDate)ToTime() time.Time {
    return time.Time(md)
}

func main()  {
    timeMap := make(map[time.Time]string)

    md1, _ := NewMyDate(2019, 1, 1, *time.UTC)
    md2, _ := NewMyDate(2019, 1, 1, *time.UTC)

    timeMap[md1.ToTime()] = "1"
    timeMap[md2.ToTime()] = "2"

    for k, v := range timeMap {
        fmt.Println(k, v)
    }
}

The output:

2019-01-01 00:00:00 +0000 UTC 1

2019-01-01 00:00:00 +0000 UTC 2

func NewMyDate(year, month, day int, tz time.Location) (MyDate, error) {
  return MyDate(time.Date(year, time.Month(month), day, 0, 0, 0, 0, &tz)), nil
}

&tz refers to the address of the NewMyDate parameter, which may be different for each call. In Go, function arguments are passed by value.

Use the same time zone for each call. For example,

package main

import (
    "fmt"
    "time"
)

type MyDate time.Time

func NewMyDate(year, month, day int, tz *time.Location) (MyDate, error) {
    return MyDate(time.Date(year, time.Month(month), day, 0, 0, 0, 0, tz)), nil
}

func (md MyDate) ToTime() time.Time {
    return time.Time(md)
}

func main() {
    timeMap := make(map[time.Time]string)

    md1, _ := NewMyDate(2019, 1, 1, time.UTC)
    md2, _ := NewMyDate(2019, 1, 1, time.UTC)

    timeMap[md1.ToTime()] = "1"
    timeMap[md2.ToTime()] = "2"

    for k, v := range timeMap {
        fmt.Println(k, v)
    }
}

Playground: https://play.golang.org/p/M10Xn4jsoKS

Output:

2019-01-01 00:00:00 +0000 UTC 2

Your timezone pointer is different every time. Fix this by providing the pointer explicitly:

func NewMyDate(year, month, day int, tz *time.Location) (MyDate, error) {
    return MyDate(time.Date(year, time.Month(month), day, 0, 0, 0, 0, tz)), nil
}

Playground: https://play.golang.org/p/M10Xn4jsoKS.

Tha map works as expected, however, your keys are not equal. If you add fmt.Println(md1.ToTime() == md2.ToTime()) you will see that.

From the documentation:

The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic.