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

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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘