英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论