如何从单个模型日期1生成一个日期从1到10的模型切片?

huangapple go评论66阅读模式
英文:

How to generate a slice of model with date running from 1 to 10, from a single model date 1?

问题

我实际上有一个类似的模型

type Price struct {
   Type  string 
   Date  time.Time
   Price float64
}

inputTime, _ := time.Parse("2006-01-02", "2022-01-01")
priceOnDate := Price{
    Type:  "A",
    Date:  inputTime,
    Price: 12.23,
}

从这个模型中,我想生成一个从1月1日到1月5日的模型切片。手动操作的话,我需要这样做

inputTime, _ := time.Parse("2006-01-02", "2014-11-12")
priceOnDate := Price{
    Type:  "A",
    Date:  inputTime,
    Price: 12.23,
}
var listOfPrice []Price

for i := 1; i < 5; i++ {
    tempPriceOnDate := priceOnDate
    tempPriceOnDate.Date = inputTime.Add(time.Hour * time.Duration(24*i))
    listOfPrice = append(listOfPrice, priceOnDate)
}
fmt.Println(listOfPrice)

然而,我觉得这种方法并不是很优化。我相信有一些包可以支持这样做。

英文:

I actually have a model like this

type Price struct {
   Type  string 
   Date  time.Time
   Price float64
}

inputTime, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2022-01-01&quot;)
priceOnDate := Price{
	Type:  &quot;A&quot;,
	Date:  inputTime,
	Price: 12.23,
}

From that I want to generate a slice of Model from day 1 January to day 5 January. Manually I have to do

inputTime, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2014-11-12&quot;)
priceOnDate := Price{
	Type:  &quot;A&quot;,
	Date:  inputTime,
	Price: 12.23,
}
var listOfPrice []Price

for i := 1; i &lt; 5; i++ {
	tempPriceOnDate := priceOnDate
	tempPriceOnDate.Date = inputTime.Add(time.Hour * time.Duration(24*i))
	listOfPrice = append(listOfPrice, priceOnDate)
}
fmt.Println(listOfPrice)

However, I feel that it is not very optimized. I believe there are packages that support doing so.

答案1

得分: 1

一些技巧:

  • 你可以直接在循环中构建所有的值。
  • 你可以预先分配好切片的大小,因为你知道它将有多少个值。
  • 你可以使用 time.AddDate
inputTime := time.Date(2014, 11, 12, 0, 0, 0, time.UTC)
nDays := 5
listOfPrice := make([]Price, nDays)
for i := 0; i < nDays; i++ {
  listOfPrice[i] = Price{
    Type: "A",
    Date: inputTime.AddDate(0, 0, i),
    Price: 12.23,
  }
}
英文:

A few tricks:

  • You could just construct all the values in the loop directly.
  • You can pre-allocate your slice since you know how many values it will have.
  • You can use time.AddDate.
inputTime := time.Date(2014, 11, 12, 0, 0, 0, time.UTC)
nDays := 5
listOfPrice := make([]Price, nDays)
for i := 0; i &lt; nDays; i++ {
  listOfPrice[i] = Price{
    Type: &quot;A&quot;,
    Date: inputTime.AddDate(0, 0, i),
    Price: 12.23,
  }
}

huangapple
  • 本文由 发表于 2022年11月9日 13:05:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/74370134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定