Chau Loi
Chau Loi

Reputation: 1225

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

I actually have a model like this

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,
}

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("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)

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

Upvotes: 1

Views: 38

Answers (1)

Austin
Austin

Reputation: 3328

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 < nDays; i++ {
  listOfPrice[i] = Price{
    Type: "A",
    Date: inputTime.AddDate(0, 0, i),
    Price: 12.23,
  }
}

Upvotes: 1

Related Questions