日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

解決Go語言time包數字與時間相乘的問題_Golang

作者:西京刀客 ? 更新時間: 2022-06-04 編程語言

背景說明:

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))

原文鏈接:https://blog.csdn.net/inthat/article/details/123895596

欄目分類
最近更新