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

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

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

问题

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

  1. type Price struct {
  2. Type string
  3. Date time.Time
  4. Price float64
  5. }
  6. inputTime, _ := time.Parse("2006-01-02", "2022-01-01")
  7. priceOnDate := Price{
  8. Type: "A",
  9. Date: inputTime,
  10. Price: 12.23,
  11. }

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

  1. inputTime, _ := time.Parse("2006-01-02", "2014-11-12")
  2. priceOnDate := Price{
  3. Type: "A",
  4. Date: inputTime,
  5. Price: 12.23,
  6. }
  7. var listOfPrice []Price
  8. for i := 1; i < 5; i++ {
  9. tempPriceOnDate := priceOnDate
  10. tempPriceOnDate.Date = inputTime.Add(time.Hour * time.Duration(24*i))
  11. listOfPrice = append(listOfPrice, priceOnDate)
  12. }
  13. fmt.Println(listOfPrice)

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

英文:

I actually have a model like this

  1. type Price struct {
  2. Type string
  3. Date time.Time
  4. Price float64
  5. }
  6. inputTime, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2022-01-01&quot;)
  7. priceOnDate := Price{
  8. Type: &quot;A&quot;,
  9. Date: inputTime,
  10. Price: 12.23,
  11. }

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

  1. inputTime, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2014-11-12&quot;)
  2. priceOnDate := Price{
  3. Type: &quot;A&quot;,
  4. Date: inputTime,
  5. Price: 12.23,
  6. }
  7. var listOfPrice []Price
  8. for i := 1; i &lt; 5; i++ {
  9. tempPriceOnDate := priceOnDate
  10. tempPriceOnDate.Date = inputTime.Add(time.Hour * time.Duration(24*i))
  11. listOfPrice = append(listOfPrice, priceOnDate)
  12. }
  13. 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
  1. inputTime := time.Date(2014, 11, 12, 0, 0, 0, time.UTC)
  2. nDays := 5
  3. listOfPrice := make([]Price, nDays)
  4. for i := 0; i < nDays; i++ {
  5. listOfPrice[i] = Price{
  6. Type: "A",
  7. Date: inputTime.AddDate(0, 0, i),
  8. Price: 12.23,
  9. }
  10. }
英文:

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.
  1. inputTime := time.Date(2014, 11, 12, 0, 0, 0, time.UTC)
  2. nDays := 5
  3. listOfPrice := make([]Price, nDays)
  4. for i := 0; i &lt; nDays; i++ {
  5. listOfPrice[i] = Price{
  6. Type: &quot;A&quot;,
  7. Date: inputTime.AddDate(0, 0, i),
  8. Price: 12.23,
  9. }
  10. }

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:

确定