Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can time.Duration use operators in Go?

from my understanding operators are only defined for builtin types and can’t be defined for user types so:

a := 1
b := 2
c := a + b // possible

but as soon as you define your own types you need to do:

a := NewType(1)
b := NewType(2)
c := a + b // is not possible
c := a.Plus(b) // is possible

but when using time.Duration I’m able to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a := time.Duration(1)
b := time.Duration(2)
c := a + b // is possible

So I probably miss something.

>Solution :

Arithmetic operators are defined for numeric types, and some of them are defined for string types. If the underlying type of a derived type supports a set of operators, those operators are also supported for the derived type.

In your example, Duration is a int64, so all operators defined for int64 works for Duration.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading