解決Go語言time包數(shù)字與時(shí)間相乘的問題
背景說明:
10 * time.Second //正常數(shù)字相乘沒錯(cuò)
但是
package main
import "time"
func main(){
connectTimeout := 10
time.Sleep(time.Second*connectTimeout)
}這樣使用會(huì)報(bào)錯(cuò)
int and time.Duration are different types. You need to convert the int to a time.Duration
原因分析:
原因:因?yàn)轭愋筒黄ヅ洌瑃ime.Duration類型 不能直接和 int類型相乘,需要先將變量轉(zhuǎn)換為time.Duration
解決方式:time.Duration(int變量))
解決方法:
要將整數(shù)個(gè)單位轉(zhuǎn)換為持續(xù)時(shí)間
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轉(zhuǎn)換為time.duration?
參考URL: https://ask.csdn.net/questions/1037457
golang time.Duration 自定義變量報(bào)錯(cuò)解決
參考文末介紹。
下面看下:golang time.Duration 自定義變量報(bào)錯(cuò)解決
對(duì)于time.Duration類型,如果采用 time.Duration類型 * int變量 會(huì)報(bào)錯(cuò),而直接和數(shù)字相乘則不會(huì)出現(xiàn);
具體是為什么呢?怎么解決呢?
錯(cuò)誤:Invalid operation: time.Millisecond * idcTimeOut (mismatched types Duration and int64)
原因:因?yàn)轭愋筒黄ヅ洌瑃ime.Duration類型 不能直接和 int類型相乘,需要先將變量轉(zhuǎn)換為time.Duration
解決方式:time.Duration(int變量))
代碼如下:
?idc := getIdc()
?? ?var idcTimeOut int64
?? ?if _, ok := IdcTimeout[idc]; ok {
?? ??? ?idcTimeOut = IdcTimeout[idc]
?? ?} else {
?? ??? ?idcTimeOut = AllTimeout
?? ?}
? ? //錯(cuò)誤寫法
? ? time.After(time.Millisecond * idcTimeOut
? ? //正確寫法
? ? time.After(time.Millisecond * time.Duration(idcTimeOut))到此這篇關(guān)于解決Go語言time包數(shù)字與時(shí)間相乘的問題的文章就介紹到這了,更多相關(guān)Go語言數(shù)字與時(shí)間相乘內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go?Error?嵌套實(shí)現(xiàn)創(chuàng)建方式
這篇文章主要介紹了Go?Error?嵌套到底是怎么實(shí)現(xiàn)的?大家都知道創(chuàng)建error有兩種方式分別是errors.new()另一種是fmt.errorf(),本文通過詳細(xì)例子給大家介紹,需要的朋友可以參考下2022-01-01
Go語言編程學(xué)習(xí)golang配置golint
這篇文章主要為大家介紹了Go語言編程學(xué)習(xí)golang配置golint的過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2021-11-11
go?sync.Once實(shí)現(xiàn)高效單例模式詳解
這篇文章主要為大家介紹了go?sync.Once實(shí)現(xiàn)高效單例模式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
windows下使用GoLand生成proto文件的方法步驟
本文主要介紹了windows下使用GoLand生成proto文件的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
golang?gorm的關(guān)系關(guān)聯(lián)實(shí)現(xiàn)示例
這篇文章主要為大家介紹了golang?gorm的關(guān)系關(guān)聯(lián)實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04
Go語言中http和mysql的實(shí)現(xiàn)代碼
本文通過實(shí)例代碼給大家介紹了Go語言中http和mysql的實(shí)現(xiàn)代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-11-11

