重新定义类型格式和方法

Here is a basic go program

package main

import (
        "fmt"
        "time"
)

type myTime time.Time

func main() {
        my := myTime(time.Now())
        fmt.Println(my)

        normal := time.Now()
        fmt.Println(normal)
}

And the corresponding output

{63547112172 291468455 0x545980}
2014-09-23 23:36:12.292132305 +0000 UTC

I would like to know why myTime prints diffrently than time.Time. They basically are supposed to be from the same type... Also, if I try to access any method of time.Time, let's say, Day, it's available for "normal" but not for "my".

Thanks!

Your new type does not inherit methods from time.Time. To quote the spec:

The declared type does not inherit any methods bound to the existing type

Since there is no String method, it won't print a meaningful value. You need to implement that yourself.

Your other option is to embed time.Time in your own type. That way you can include the functionality of time.Time but also add your own functionality.

Playground link: http://play.golang.org/p/PY6LIBoP6H

type myTime struct {
    time.Time
}

func (t myTime) String() string {
    return "<Custom format here>"
}

func main() {
    my := myTime{time.Now()}
    fmt.Println(my)

    normal := time.Now()
    fmt.Println(normal)
}

fmt.Println uses the String() method (or rather the fmt.Stringer interface) when formatting a type as a string, if it is available. When you create a new type using an underlying type (in your case time.Time):

type myTime time.Time

You will not inherit the methodset of the underlying type. Therefore, myTime has no String() method, so fmt will use the default format for a struct.