时间:2023-01-28 10:34:07 | 栏目:Golang | 点击:次
10 * time.Second //正常数字相乘没错
但是
package main import "time" func main(){ connectTimeout := 10 time.Sleep(time.Second*connectTimeout) }
这样使用会报错
int and time.Duration are different types. You need to convert the int to a time.Duration
原因:因为类型不匹配,time.Duration类型 不能直接和 int类型相乘,需要先将变量转换为time.Duration
解决方式:time.Duration(int变量))
要将整数个单位转换为持续时间
seconds := 10 ctx, cancel := context.WithTimeout(context.Background(), time.Duration(seconds) * time.Second) //ctx, cancel := context.WithCancel(context.Background()) defer cancel()
// Common durations. There is no definition for units of Day or larger // to avoid confusion across daylight savings time zone transitions. // // To count the number of units in a Duration, divide: // second := time.Second // fmt.Print(int64(second/time.Millisecond)) // prints 1000 // // To convert an integer number of units to a Duration, multiply: // seconds := 10 // fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
Golang:如何将int转换为time.duration?
参考URL: https://ask.csdn.net/questions/1037457
golang time.Duration 自定义变量报错解决
参考文末介绍。
下面看下:golang time.Duration 自定义变量报错解决
对于time.Duration类型,如果采用 time.Duration类型 * int变量 会报错,而直接和数字相乘则不会出现;
具体是为什么呢?怎么解决呢?
错误:Invalid operation: time.Millisecond * idcTimeOut (mismatched types Duration and int64)
原因:因为类型不匹配,time.Duration类型 不能直接和 int类型相乘,需要先将变量转换为time.Duration
解决方式:time.Duration(int变量))
代码如下:
idc := getIdc() var idcTimeOut int64 if _, ok := IdcTimeout[idc]; ok { idcTimeOut = IdcTimeout[idc] } else { idcTimeOut = AllTimeout } //错误写法 time.After(time.Millisecond * idcTimeOut //正确写法 time.After(time.Millisecond * time.Duration(idcTimeOut))