Golang 的 Int 标志和 time.After

Golang's Int flag and time.After

我在尝试 运行 与此类似的东西时遇到 invalid operation: *timeout * time.Second (mismatched types int and time.Duration) 错误

timeout := flag.Int("timeout", 30, "The time limit for answering questions.")
flag.Parse()
timeoutCh := time.After(*timeout * time.Second)

为了确定,我使用 reflect.TypeOf() 检查了 *timeout 的类型,它实际上是一个 int。但是如果我做 timeoutCh := time.After(30 * time.Second) 或使用任何其他 int 值代码工作。

我在这里错过了什么?

timeoutCh := time.After(time.Duration(*timeout) * time.Second)

您必须将类型 int*timeout 转换为类型 time.Duration. The reason why time.After(30 * time.Second) works is that 30 is untyped and is converted to the type of time.Second which is time.Duration. See https://golang.org/ref/spec#Operators。同样,此代码有效

x := uint(42)
if x == 42 {
    println("works!")
}

但是这段代码无法编译

x := uint(42)
y := 42 // defaults to type int
if x == y {
    println("this won't complile!")
}

您不能将两种不同的类型相乘,因此您需要将整数转换为 time.Duration 类型。您可以像这样简单地转换它来做到这一点:

time.Duration(*timeout)

"unit" 的时间在技术上是一纳秒,而 time.Second 是一秒的纳秒。虽然数学计算出来了,所以你可以简单地这样说 3 秒:

time.Duration(3) * time.Second