碰到一个Golang time.Duration的问题,编译的时候总是报
`time.Second*connectTimeout(mismatched types time.Durationandint)`
问题重现:
~~~
package main
import "time"
func main(){
connectTimeout := 10
time.Sleep(time.Second * connectTimeout)
}
~~~
解决的方法:
~~~
connectTimeout := 10
time.Sleep(time.Duration(connectTimeout) * time.Second)
~~~
产生这个问题的原因是:
> int and time.Duration are different types. You need to convert the int to a time.Duration
Golang的和时间相关的可以直接用数字,但不能是float浮点型,也不能直接是数值型变量.
~~~
time.Sleep(1 * time.Second) //可以
time.Sleep(1.1 * time.Second) //不可以
time.Sleep(time.Duration(yourTime) * time.Second) //可以
time.Sleep(yourTime * time.Second) //不可以
~~~