英文:
Strange variable passed to function? time.Minute not being passed as a minute
问题
我有一个函数:
func myFunc(mycontext context.Context, duration time.Duration, f someFunc) {
for {
select {
case <-time.After(duration):
// 做一些事情
case <-mycontext.Done():
// 其他事情
}
}
}
这样调用:
duration := time.Minute
go myFunc(mycontext, duration, myFuncPointer)
今天我注意到这个函数永远不会退出。在暂停和检查go线程时,我发现我的duration变量具有以下值:
github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)
为什么它具有这个值而不是我设置的一分钟的持续时间?而且duration在任何时候都没有重新赋值,所以我认为不是这个问题。
英文:
I have a function that is
func myFunc(mycontext context.Context, duration time.Duration, f someFunc) {
for {
select {
case <- time.After(duration):
// do some stuff
case <-mycontext.Done():
// Other stuff
}
}
This is called with
duration := time.Minute
go myFunc(mycontext, duration, myFuncPointer)
Today I noticed this function never exits. Upon pausing and inspecting the gothread I see that my duration variable has this value
github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)
Why does it have this value and not my one minute duration? Also duration never gets reassigned at any point so I don't think its that.
答案1
得分: 3
我看到我的持续时间变量具有这个值
github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)
为什么它具有这个值而不是我的一分钟持续时间?
阅读Go标准库time包的文档。
type Duration int64
Duration表示两个时刻之间经过的时间,以int64纳秒计数。
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
time.Minute
是60000000000
纳秒。
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(int64(time.Minute))
}
https://go.dev/play/p/YVx4ddJYnv6
60000000000
英文:
> I see that my duration variable has this value
>
> github.com/cenkalti/backoff/v4.DefaultMaxInterval (60000000000)
>
> Why does it have this value and not my one minute duration?
Read the Go standard library package time documentation.
> type Duration int64
>
> A Duration represents the elapsed time between two instants as an int64 nanosecond count.
> const (
> Nanosecond Duration = 1
> Microsecond = 1000 * Nanosecond
> Millisecond = 1000 * Microsecond
> Second = 1000 * Millisecond
> Minute = 60 * Second
> Hour = 60 * Minute
> )
time.Minute
is 60000000000
nanoseconds.
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(int64(time.Minute))
}
https://go.dev/play/p/YVx4ddJYnv6
60000000000
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论