[英]time.Duration * time.Duration applied twice
Assuming I have:假设我有:
t := 10 * time.Second // 10s,
what's going on behind the scene when time.Second is applied again?当 time.Second 再次应用时,幕后发生了什么?
tt := t * time.Second // -2346317h47m53.709551616s
https://play.golang.org/p/upyjGgsuVQm https://play.golang.org/p/upyjGgsuVQm
A time.Duration
value is a numeric value that represents number of nanoseconds . time.Duration
值是表示纳秒数的数值。
A Duration represents the elapsed time between two instants as an int64 nanosecond count. Duration 将两个瞬间之间的经过时间表示为 int64 纳秒计数。 The representation limits the largest representable duration to approximately 290 years.该表示将最大可表示持续时间限制为大约 290 年。
type Duration int64
Whatever arithmetic you perform on time.Duration
values, they are performed numerically just as on int64
values.无论您在time.Duration
值上执行什么算术运算,它们都以数字方式执行,就像在int64
值上一样。
time.Second
is a (typed) constant holding the number of nanoseconds in one second, so multiplying it by 10
will give you the number of nanoseconds in 10 seconds. time.Second
是一个(键入的)常数,保存一秒内的纳秒数,因此将其乘以10
将得到 10 秒内的纳秒数。 This fits "perfectly" into an int64
number.这“完全”适合int64
数字。 As the documentation states, int64
may store number of nanoseconds up to about 290 years.正如文档所述, int64
最多可以存储大约 290 年的纳秒数。
Now if t
holds number of nanonseconds in 10 seconds, and you multiply that by the number of nanoseconds in 1 second, using 64-bit integers, that will overflow:现在,如果t
在 10 秒内保持纳秒数,然后将其乘以 1 秒内的纳秒数,使用 64 位整数,则会溢出:
fmt.Println(math.MaxInt64)
fmt.Print(int64(10*time.Second), "*", int64(time.Second))
Outputs:输出:
9223372036854775807
10000000000*1000000000
Note that t
is a variable, and so overflow is OK.注意t
是一个变量,所以溢出是可以的。 Constants in Go are exact values and do not overflow. Go 中的常量是精确值,不会溢出。 So 10 * time.Second * time.Second
would be a constant value that does not fit into int64
and hence it gives an error when you try to assign the result to a variable that's backed by an int64
.所以10 * time.Second * time.Second
将是一个不适合int64
的常量值,因此当您尝试将结果分配给由int64
支持的变量时会出错。 For details see Does Go compiler's evaluation differ for constant expression and other expression有关详细信息,请参阅Go 编译器对常量表达式和其他表达式的评估是否不同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.