On Wed, 19 Jan 2022 at 04:19, Ian Lance Taylor <i...@golang.org> wrote:
> On Mon, Jan 17, 2022 at 9:53 PM Corin Lawson <corin.law...@gmail.com> > wrote: > > > > 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 > > } > > ``` > > A time.Duration is just an integer. The standard text marshaling and > unmarshaling work fine. > 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+unsubscr...@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 > . > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJhgacjJq7Xp-JzTP4PvyVKXzFkAyRYQHWnQ%2BtgGzRaqvEFWpA%40mail.gmail.com.