"Overriding" the String method of time.Time

I’m trying to “override” (not sure if that is the right term) the String() method of the time.Time struct so that it returns a time in the format of RFC3339 (e.g. 2009-11-10T23:00:00Z) instead of the default (e.g. 2009-11-10 23:00:00 +0000 UTC m=+0.000000001)

I can do it this way (method 1):

type TimeTypeA struct {
  time.Time
}

func (d *TimeTypeA) String() string {
  return d.Format(time.RFC3339)
}

func main() {
  t1 := time.Now()
  fmt.Printf("t1 is %v\n", t1)

  t2 := TimeTypeA{time.Now()}
  fmt.Printf("t2 is %v\n", &t2)
}

But if I do it this way (method 2):

type TimeTypeB time.Time

func (d TimeTypeB) String() string {
  return d.Format(time.RFC3339)
}

The compiler complains that “type TimeTypeB has no field or method Format”.

So my questions are:

  1. Why is this so?
  2. What are the methods called? (I think the first one is called composition, but what about the second one?)
  3. What is the right way, if possible, to make it work for method 2?
1 Like
  1. Because timeB it’s separate type and you don’t define Format method. And time.Time struct is embedded in type timeA.

  2. It’s type aliasing.

  3. For example so:

     type TimeTypeB time.Time
     
     func (d TimeTypeB) String() string {
       return time.Time(d).Format(time.RFC3339)
     }
3 Likes

Thanks for the answer! Very clear! :grinning:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.