英文:
How to make an array in struct to use it in a loop?
问题
我有一个包含34个产品的CSV文件,我想在HTML文件中逐个使用它们。为此,我需要一个数组键,以便我可以逐个在HTML文件中使用值。
问题:
- 每当我执行这段代码时,它只打印最后一个产品名称。
- 我不知道如何在结构体中创建一个数组,以便我可以在for循环中使用它作为键。
代码:
type List struct {
ProductsList string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i++ {
user = List{
ProductsList: products.AccessData(i),
}
}
HomeTmpl.Execute(w, user)
}
英文:
I have 34 products in a CSV file and I want to use each of them in an HTML file. For this purpose, I need an array key so that I can use a value in an HTML file one by one.
Problem
- Whenever I execute this code, it prints only the last product name.
- I don't know how to make an array in a struct so that I can use it as a key using the for-loop.
Code
type List struct {
ProductsList string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i++ {
user = List{
ProductsList: products.AccessData(i),
}
}
HomeTmpl.Execute(w, user)
}
答案1
得分: 0
我们可以通过这样声明[]string
来将ProductsList
变成一个切片(即动态数组)。然后我们可以使用append
函数将元素添加到切片的末尾。这将创建一个切片,其中切片的索引与i
相匹配。
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i++ {
user.ProductsList = append(user.ProductsList, products.AccessData(i))
}
HomeTmpl.Execute(w, user)
}
英文:
We can make ProductsList
a slice(fancy array) by delaring it like this []string
. We can then use the append
function to add elements to the end of the slice. This will make a slice where the index of the slice matches i
.
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
var user List
for i := 0; i < 34; i++ {
user.ProductsList = append(user.ProductsList, products.AccessData(i))
}
HomeTmpl.Execute(w, user)
}
答案2
得分: -1
尝试这样做。
我将ProductList属性更改为切片字符串。
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
AllData := []string{}
for i := 0; i < 34; i++ {
AllData = append(AllData, products.AccessData(i))
}
user := List{ ProductsList: AllData }
// user.ProducList = ["yourdata","hello","example","and more"]
HomeTmpl.Execute(w, user)
}
英文:
Try this.
I changed ProductList properties to slice string
type List struct {
ProductsList []string
}
func Home(w http.ResponseWriter, r *http.Request) {
AllData := []string{}
for i := 0; i < 34; i++ {
AllData = append(AllData, products.AccessData(i))
}
user := List{ ProductsList: AllData }
// user.ProducList = ["yourdata","hello","example","and more"]
HomeTmpl.Execute(w, user)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论