我不能在golang中使用变量进行时间计算吗?

Can't I use variables for time calculations in golang?

我正在计算 10 分钟前的时间。 为什么我不能使用变量(可用于 for 循环)进行此计算。 见-

package main

import (
    "fmt"
    "time"
)

func main() {

    // the time now
    fmt.Println(time.Now())

    // the time 50 minutes ago - WORKS
    diff := (60 - 10) * time.Minute
    newTime := time.Now().Add(-diff)
    fmt.Println(newTime)

    // the time 50 minutes ago - DOESN'T WORKS!
    i := 10
    diff = (60 - i) * time.Minute
    newTime = time.Now().Add(-diff)
    fmt.Println(newTime)
}

为什么 diff = (60 - i) * time.Minute 不起作用? 这是我得到的错误 -

prog.go:20: invalid operation: (60 - i) * time.Minute (mismatched types int and time.Duration)

围棋游乐场:https://play.golang.org/p/TJ03K0ULg2

非常感谢!

如错误所述,您的类型不匹配。将整数结果转换为 time.Duration:

diff = time.Duration(60-i) * time.Minute

time.Duration实际上是类型int64,所以如果你想使用变量来做你想要的,只需将变量声明为time.Duration,就像这样:

package main

import (
    "fmt"
    "time"
)

func main() {

    // the time now
    fmt.Println(time.Now())

    // the time 50 minutes ago - WORKS
    diff := (60 - 10) * time.Minute
    newTime := time.Now().Add(-diff)
    fmt.Println(newTime)

    // the time 50 minutes ago - DOESN'T WORKS!
    var i time.Duration
    diff = (60 - i) * time.Minute
    newTime = time.Now().Add(-diff)
    fmt.Println(newTime)
}