[英]Golang: How to convert int to calculate into time.duration
我是GoLang的新手,而現在卻茫然為什么編譯器不接受特定的代碼行。
我有一個在撥號時創建超時的工作示例:
conn, err := grpc.Dial(*connAddress,
grpc.WithInsecure(),
grpc.WithBlock(), // will block till the connection is available
grpc.WithTimeout(100*time.Second)) // times out after 100 seconds
現在那里的硬編碼100不是很好,所以我想通過一個標志使該命令行變量如下:
connTimeout := flag.Int64("connection-timeout", 100, "give the timeout for dialing connection x")
...
conn, err := grpc.Dial(*connAddress,
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithTimeout(*connTimeout*time.Second))
但是,這會產生以下編譯錯誤:
int64和time.Duration類型不匹配
因此,顯然我不能直接使用int64標志變量來計算持續時間,但是數字可以嗎?
最終我找到了一個通過創建與time.Duration相關的變量來使用flag變量的解決方案:
var timeoutduration = time.Duration(*distributorTimeout) * time.Second
// create distributor connection
conn, err := grpc.Dial(*connAddress,
grpc.WithBlock(),
grpc.WithTimeout(timeoutduration))
上面的代碼似乎按預期方式工作:只要給定命令行參數(默認為100),就會嘗試撥號,然后拋出一條消息,提示無法建立連接。 好。
但是:如何不能直接使用int64標志變量來計算時間。持續時間,換句話說,數字100與包含int64的變量之間的golang有什么區別?
grpc.WithTimeout(100*time.Second)
grpc.WithTimeout(*connTimeout*time.Second)
grpc.WithTimeout(100*time.Second)
和grpc.WithTimeout(*connTimeout*time.Second)
並非由於可分配性規則 :
后者滿足上述條件,而前者滿足
x
是可由類型T
的值表示的無類型常量。 規則
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.