Home >Backend Development >Golang >Why Does My Custom Time Type Alias Output Unexpected Results When Unmarshaling?
Unexpected Output with Custom Time Type Alias
When trying to unmarshal a custom Time type alias, the resulting output may be unexpected. Consider the following code:
<code class="go">type Time time.Time func main() { // Simplified unmarshal code for brevity st := Time(time.Parse(time.RFC3339, "2021-05-21T03:10:20.958450Z")) fmt.Printf("%v\n", st) }</code>
Expecting formatted time, the output instead displays the following:
&{958450000 63757163420 <nil>}
Root Cause
The issue lies in the missing implementation of fmt.Stringer for the Time type. By default, fmt uses its own formatting logic, which displays the fields of the underlying time.Time value in curly braces.
Solutions
To resolve this, there are two options:
Add a String method to your Time type that delegates to the String method of time.Time:
<code class="go">func (t Time) String() string { return time.Time(t).String() }</code>
Change the Time type to embed time.Time instead of aliasing it. This will automatically inherit the String method and all other methods of time.Time:
<code class="go">type Time struct { time.Time }</code>
Additional Improvements
<code class="go">func (st *Time) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } t, err := time.ParseInLocation("2006-01-02T15:04:05", s, time.UTC) if err != nil { return err } *st = Time(t) return nil }</code>
The above is the detailed content of Why Does My Custom Time Type Alias Output Unexpected Results When Unmarshaling?. For more information, please follow other related articles on the PHP Chinese website!