常见的time duration问题
invalid operation: num * time.Second (mismatched types int64 and time.Duration)
invalid operation: num * time.Second (mismatched types int and time.Duration)
比如用math/rand得到一个随机数,然后time.sleep()等待…
num := rand.Int31n(10)
time.sleep(num * time.Second)
那么会遇到下面的问题:
# command-line-arguments
./lock.go:88: invalid operation: int(DefaultTimeout) * time.Second (mismatched types int and time.Duration)
解决的方法:
使用time.Duration转换类型
num := rand.Int31n(10)
time.Sleep(time.Duration(num) * time.Second)
产生的原因:
sleep接收的参数为Duration类型
func Sleep(d Duration) ...
当我们要实现5秒时,方法为 5 * second,second又是1000 * Millisecond,而Millisecond又是1000 * Microsecond,Microsecond又是1000 * Nanosecond,Nanosecond为一个纳秒,他的类型就是Duration。最后5秒拿到的数应该是 5,000,000,000数值
type Duration int64
const (
Nanosecond Duration = 1 // 设为1个纳秒
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
那么为什么我们可以直接使用 time.Sleep(5 * time.Second) ?
// xiaoru.cc
package main
import (
"time"
)
func main() {
time.Sleep(time.Duration(2) * time.Second)
time.Sleep(3 * time.Second)
}
通过汇编分析可以看到golang已帮我优化了time.Duration的转换。
0x005d 00093 (GOROOT/src/fmt/print.go:274) MOVQ CX, 16(SP)
0x0062 00098 (GOROOT/src/fmt/print.go:274) MOVQ 1, 24(SP)
0x006b 00107 (GOROOT/src/fmt/print.go:274) MOVQ 1, 32(SP)
0x0074 00116 (GOROOT/src/fmt/print.go:274) CALL fmt.Fprintln(SB)
0x0079 00121 (kk.go:10) MOVQ 2000000000, (SP)
0x0081 00129 (kk.go:10) CALL time.Sleep(SB)
0x0086 00134 (kk.go:11) MOVL3000000000, AX
0x008b 00139 (kk.go:11) MOVQ AX, (SP)
0x008f 00143 (kk.go:11) CALL time.Sleep(SB)
0x0094 00148 (kk.go:13) PCDATA 1,2