繁体   English   中英

Golang:如何将int转换为time.duration

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM