请使用golang实现 timeduration 累计和
以下是使用Golang实现time.Duration累计和的示例代码:
package main
import (
"fmt"
"time"
)
func main() {
durations := []time.Duration{
2 * time.Second,
5 * time.Second,
1 * time.Minute,
}
totalDuration := sumDurations(durations)
fmt.Println(totalDuration)
}
func sumDurations(durations []time.Duration) time.Duration {
total := time.Duration(0)
for _, d := range durations {
total += d
}
return total
}
在上面的示例代码中,我们定义了一个包含多个time.Duration的切片durations。然后,我们使用sumDurations函数对这些时间段进行累加,并返回累加结果。
sumDurations函数首先将total初始化为0,然后使用for循环遍历durations切片,将每个时间段都加到total中。最后,将累加的结果作为time.Duration类型返回。
在main函数中,我们调用sumDurations函数并将结果打印出来
原文地址: https://www.cveoy.top/t/topic/ikfu 著作权归作者所有。请勿转载和采集!