Home >Backend Development >Golang >Why Does My Custom Time Type Alias Output Unexpected Results When Unmarshaling?

Why Does My Custom Time Type Alias Output Unexpected Results When Unmarshaling?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 17:12:02949browse

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:

  1. Implement fmt.Stringer:

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>
  1. Embed time.Time:

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

  • Always use json.Unmarshal to decode JSON strings to avoid manual parsing.
  • Consider using time.ParseInLocation for precise control over time zone interpretation:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn