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

Mary-Kate Olsen
Release: 2024-10-28 17:12:02
Original
885 people have browsed it

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>
Copy after login

Expecting formatted time, the output instead displays the following:

&{958450000 63757163420 <nil>}
Copy after login

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>
Copy after login
  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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!