duanliao2310 2017-05-10 12:06 采纳率: 100%
浏览 7628
已采纳

Golang:如何将int转换为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

很明显,我不能直接使用int 64标志变量来计算一个持续时间,但是一个单独的数字可以吗?最后,通过创建一个与时间相关的变量,我找到了一个使用标志变量的解决方案。

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

上述操作似乎如出一辙:只要给定命令行参数(默认为100),拨号就会尝试,并且会抛出无法建立连接的消息。

然而:为什么直接使用int 64标志变量计算时间是不可能的,换句话说,数字100和包含int 64的变量对于golang有什么区别?

  • 写回答

1条回答 默认 最新

  • dongshen6060 2017-05-10 12:21
    关注

    grpc.WithTimeout(100*time.Second) and grpc.WithTimeout(*connTimeout*time.Second) does not because of assignability rules:

    the latter expression satisfies none of those, and the former satisfies the

    • x is an untyped constant representable by a value of type T.

    rule

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计