No time.Duration#UnmarshalText; is there a good reason?

198 views
Skip to first unread message

Corin Lawson

unread,
Jan 18, 2022, 12:52:55 AM1/18/22
to golang-nuts
It seems obvious (to me) that the encoding.TextUnmarshaler interface could be implemented for time.Duration (it is implemented for time.Time, afterall).

The fact that it is not gives me pause... is there a good reason that the stdlib has not done this?  What issues am I facing if I do this: https://go.dev/play/p/nHBfS7TJQtJ

```
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (d *Duration) UnmarshalText(data []byte) error {
        val, err := time.ParseDuration(string(data))
        *d = Duration(val)
        return err
}
```

Cheers,
Corin.

Ian Lance Taylor

unread,
Jan 18, 2022, 11:19:44 PM1/18/22
to Corin Lawson, golang-nuts
A time.Duration is just an integer. The standard text marshaling and
unmarshaling work fine.

Ian

Corin Lawson

unread,
Jan 18, 2022, 11:32:05 PM1/18/22
to golang-nuts
> The standard text marshaling and unmarshaling work fine.

Ok, I get you.

I guess I'm looking for something a little more human friendly than nanoseconds!

In that case I'll proceed with my new-type, thanks!

roger peppe

unread,
Jan 19, 2022, 6:55:49 AM1/19/22
to Ian Lance Taylor, Corin Lawson, golang-nuts
They do work fine in the technical sense, but marshalling a 1s duration as 1000000000 doesn't make for a particularly readable specification of a duration when found in configuration (it's so easy to misread the number of digits). I've often wrapped a time.Duration in a type that implements marshaling and unmarshaling so it's possible to write 1s, 500ms, etc.
 
Unfortunately I don't believe that's possible to add retrospectively because marshaling using Duration.String would break any existing users that expect a number.

  cheers,
    rog.


Ian

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUbSaTJ15zT7ksQmDMaf2oq%2B0oY5uN-kzzKHXa-6JjnJw%40mail.gmail.com.

Tamás Gulácsi

unread,
Jan 20, 2022, 12:37:47 AM1/20/22
to golang-nuts
time.Duration.String() already does the pretty printing: https://pkg.go.dev/time@master#Duration.String
time.ParseDuration is the parser which could be used in UnmarshalText.
Reply all
Reply to author
Forward
0 new messages