time.Duration在Go语言中如何使用运算符?

huangapple go评论65阅读模式
英文:

How can time.Duration use operators in Go?

问题

根据我的理解,运算符只能用于内置类型,不能用于用户自定义类型。所以:

a := 1
b := 2
c := a + b // 可行

但是,一旦你定义了自己的类型,你需要这样做:

a := NewType(1)
b := NewType(2)
c := a + b // 不可行
c := a.Plus(b) // 可行

但是,当使用time.Duration时,我可以这样做:

a := time.Duration(1)
b := time.Duration(2)
c := a + b // 可行

所以我可能漏掉了什么。

英文:

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.

答案1

得分: 2

算术运算符适用于数值类型,并且其中一些运算符适用于字符串类型。如果派生类型的基础类型支持一组运算符,那么这些运算符也适用于派生类型。

在你的例子中,Duration 是一个 int64 类型,所以所有定义给 int64 的运算符也适用于 Duration

英文:

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.

huangapple
  • 本文由 发表于 2023年3月29日 00:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75868699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定