Search code examples
gooperator-overloadingoperators

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:

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.