英文:
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("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.
答案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 < nDays; i++ {
listOfPrice[i] = Price{
Type: "A",
Date: inputTime.AddDate(0, 0, i),
Price: 12.23,
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论