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

Golang: How to convert int to calculate into time.duration

我是GoLang的新手,目前不知为什么编译器不接受特定的代码行。

我有这个在拨号时创建超时的工作示例:

1
2
3
4
    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不是很好,所以我想通过一个标志使该命令行变量如下:

1
2
3
4
5
6
    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))

但是,这会产生以下编译错误:

mismatched types int64 and time.Duration

因此,显然我不能直接使用int64标志变量来计算持续时间,但是数字可以吗?

最终我找到了通过创建与time.Duration有关的变量来使用flag变量的解决方案:

1
2
3
4
5
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)并非由于可分配性规则:

后者满足上述条件,而前者满足

  • x是可以用类型T的值表示的无类型常量。

规则