首页 > 解决方案 > `foo.Seconds()`(类型 time.Duration)错误 - 不能使用 'd.Step.Seconds()'(类型 float64)作为类型 time.Duration

问题描述

我还是很陌生……所以,

我的问题的症结可以总结为:我正在准备将数据发送到远程 API,该 API 要求此字段为一种time.Duration类型,我试图将其作为秒的字符串类型发送,###s并将time.ParseDuration()其发送到秒,但这是一个错误。

type Duration struct {
    Duration time.Duration
    Step     time.Duration
}

// Needs to return a structure containing a duration formatted
// item and an item which is strictly in `seconds` format IE 
// `int` or `float` `+` `"s"`.
func getDuration(pr *PromRequest) (Duration, error) {
    duration, err := time.ParseDuration(pr.TimeRange)
    if err != nil {
        return Duration{}, nil
    }

    timeValue, err := strconv.Atoi(pr.TimeRange[:len(pr.TimeRange)-1])
    if err != nil {
        return Duration{}, err
    }

    // convert day value to day in hours
    step := time.Duration(int64(24*timeValue) * 60 / 14)

    return Duration{
        Duration: duration,
        Step:     step, // <-- should be a time.Duration type...
    }, nil
}

//    \/\/hatever
func getMetricsWithRange(pr *PromRequest) (model.Value, error) {
    d, err := getDuration(pr)
    if err != nil {
        e := fmt.Errorf("unable to translate received time into proper parsed time signature: %s", err)
        fmt.Println(e)
        return nil, err
    }

...
    r := v1.Range{
        Start: time.Now().Add(-d.Duration),
        End:   time.Now(),
        Step:  d.Step.Seconds(),  // <-- error lands here stating it's a float64
    }
...
}

** 编辑 **

所以我想我现在理解我的误解了。time.Duration()返回一个 time.Duration 类型,然后可以通过它发送.Seconds(),它返回一个float64

在调用返回的结构的调用者中,当我打印实例变量的值时,它会是 NOT time.Duration。我需要它在几秒钟内以time.Duration的形式出现###s,我知道time.Duration这是行不通的。调用.Seconds()它失败并出现错误Cannot use 'd.Step.Seconds()' (type float64) as type time.Duration

好的,所以我的误解来自几个因素。一:我真的很累。二:我是新手,一般来说是静态类型的语言。三:我认为我需要v1.Range.Step在几秒钟内发送,这是错误的。time.Duration我查看了将值转换为秒本身的接收代码。

现在,这个问题的很大一部分来自我的前端代码使用d字符串中的字母在几天内发送一个值。time.ParseDuration()不处理d天数,所以days我认为我会简单地以秒为单位传递一个时间值,而不是使用。

事实证明,解决此问题的最简单方法是简单地seconds从前端发送。我永远无法让 go 代码正常工作。

标签: datetimego

解决方案


Duration.Seconds()返回一个float64值,因为持续时间值可能不是一整秒,并且它可能有十进制数字来表示确切的持续时间。如果Step变量是四舍五入到最接近秒的持续时间,请使用Duration.Round(time.Second)

...
Step: Step.Round(time.Second)

这将为您提供一个四舍五入到一秒的持续时间。

如果你想获得秒值,那不是持续时间,它只是一个整数:

...
Step: int(Step.Seconds())

但是,在这种情况下,结果Step不是持续时间,而只是一个给出秒数的 int 值。


推荐阅读