您现在的位置是:网站首页> 编程资料编程资料

解决Go语言time包数字与时间相乘的问题_Golang_

2023-05-26 328人已围观

简介 解决Go语言time包数字与时间相乘的问题_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))

到此这篇关于解决Go语言time包数字与时间相乘的问题的文章就介绍到这了,更多相关Go语言数字与时间相乘内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网