Go 戈朗';s Int标志和时间。在

Go 戈朗';s Int标志和时间。在,go,time,flags,Go,Time,Flags,我得到一个无效操作:*timeout*time.Second(int和time.Duration类型不匹配)尝试运行类似于此的操作时出错 timeout := flag.Int("timeout", 30, "The time limit for answering questions.") flag.Parse() timeoutCh := time.After(*timeout * time.Second) 为了确保这一点,我使用reflect.TypeOf()检查了*timeout的类型

我得到一个
无效操作:*timeout*time.Second(int和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)
您必须将
*timeout
类型
int
转换为type。
time.After(30*time.Second)
之所以有效,是因为
30
是非类型化的,并且被转换为
time.Second
的类型。看见类似地,此代码也可以工作

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)
从技术上讲,时间的“单位”是一纳秒和时间。秒是相当于一秒的纳秒。不过,数学是可行的,所以你可以简单地说3秒钟这样的话:

time.Duration(3) * time.Second

“除了移位运算外,如果一个操作数是非类型常量,而另一个操作数不是,则该常量将转换为另一个操作数的类型。”我不知道!非常感谢。