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

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

mismatched types int64 and time.Duration

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

最终我找到了使用标志变量的解决方案,方法是先创建一个与 time.Duration 相关的变量:

var timeoutduration = time.Duration(*distributorTimeout) * time.Second
    // create distributor connection
    conn, err := grpc.Dial(*connAddress,
        grpc.WithBlock(),
        grpc.WithTimeout(timeoutduration)) 

以上似乎按预期工作:只要给定命令行参数(默认 100),就会尝试拨号,然后抛出无法建立连接的消息。好

但是:为什么不能直接使用 int64 标志变量来计算 time.Duration,换句话说,对于 golang,数字 100 和包含 int64 的变量有什么区别?

grpc.WithTimeout(100*time.Second)grpc.WithTimeout(*connTimeout*time.Second) 不是因为 assignability rules:

后一个表达式满足none个,前者满足

  • x 是一个无类型常量,可由 T.
  • 类型的值表示

规则