Techradar
Techradar

Reputation: 4144

Golang custom type fmt printing

I have a custom type like this:

type Timestamp struct {
    Time time.Time  
}
// some more methods...

Now when I print an instance of it using fmt:

test := Timestamp{
    Time: time.Now(),
}
fmt.Println("TEST:", test)

the output is:

TEST: {2009-11-10 23:00:00 +0000 UTC m=+0.000000001}

How can I add custom formatting to the custom type to pretty print the output like 2009-11-10T23:00:00Z in cases where it should be printed using fmt Functions (Println etc..)?

Upvotes: 1

Views: 3487

Answers (1)

Techradar
Techradar

Reputation: 4144

It is as simple as adding this function:

func (ts Timestamp) Format(f fmt.State, c rune) {
    f.Write([]byte(ts.Time.Format(time.RFC3339)))
}

Output:

TEST: 2020-05-01T08:25:14Z

Upvotes: 3

Related Questions