代码之家  ›  专栏  ›  技术社区  ›  Wilder Galvao

Golang的Int标志和时间。[副本]之后

  •  1
  • Wilder Galvao  · 技术社区  · 8 年前

    我得到一个 invalid operation: *timeout * time.Second (mismatched types int and time.Duration) 尝试运行类似的操作时出错

    timeout := flag.Int("timeout", 30, "The time limit for answering questions.")
    flag.Parse()
    timeoutCh := time.After(*timeout * time.Second)
    

    为了确定,我检查了 *timeout 使用 reflect.TypeOf() 事实上 int 。但如果我这样做了 timeoutCh := time.After(30 * time.Second) 或使用任何其他 内景 重视代码的工作。

    我错过了什么?·

    2 回复  |  直到 8 年前
        1
  •  2
  •   Jake Burkhead    8 年前
    timeoutCh := time.After(time.Duration(*timeout) * time.Second)
    

    您必须转换 *timeout 哪种类型 int 至类型 time.Duration 。原因是 time.After(30 * time.Second) 工作是这样的 30 未类型化,并转换为 time.Second 这是 时间期间 。看见 https://golang.org/ref/spec#Operators 。类似地,此代码也起作用

    x := uint(42)
    if x == 42 {
        println("works!")
    }
    

    但这段代码无法编译

    x := uint(42)
    y := 42 // defaults to type int
    if x == y {
        println("this won't complile!")
    }
    
        2
  •  2
  •   t j Kabeer Shaikh    8 年前

    不能将两种不同的类型相乘,因此需要将整数转换为时间。持续时间类型。您可以这样简单地进行铸造:

    time.Duration(*timeout)
    

    时间的“单位”在技术上是纳秒和时间。秒是相当于1秒的纳秒。不过,数学算出来了,所以你可以简单地这样说3秒钟:

    time.Duration(3) * time.Second