Golang结构体数组的值在循环中没有追加。

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

Golang struct array values not appending In loop

问题

这是我的代码:

package main

import(
	"fmt"
)

type Category struct {
	Id   int
	Name string
}

type Book struct {
	Id         int
	Name       string
	Categories []Category
}

func main() {
	var book Book

	book.Id = 1
	book.Name = "Vanaraj"

	for i := 0; i < 10; i++ {
		book.Categories = append(book.Categories, Category{
			Id : 10,
			Name : "Vanaraj",
		})
	}

	fmt.Println(book)
}

我需要将值追加到categories中。这些值只追加了一次,但我需要将值追加到数组中。

如何修复这个问题?

英文:

This is my code:

package main

import(
	&quot;fmt&quot;
)

type Category struct {
	Id   int
	Name string
}

type Book struct {
	Id         int
	Name       string
	Categories []Category
}

func main() {
	var book Book

	book.Id = 1
	book.Name = &quot;Vanaraj&quot;

	for i := 0; i &lt; 10; i++ {
		book.Categories = []Category{
			{
				Id : 10,
				Name : &quot;Vanaraj&quot;,
			},
		}
	}

	fmt.Println(book)
}

I need to append the values to the categories. The values are appending only one time. But I need to append the values to the array.

How to fix this?

答案1

得分: 18

你在每次循环迭代中都没有向book.Categories添加任何内容,你总是创建一个新的切片,并将其赋值给book.Categories

如果你想要添加值,可以使用内置的append()函数:

for i := 0; i < 10; i++ {
    book.Categories = append(book.Categories, Category{
        Id:   10,
        Name: "Vanaraj",
    })
}

输出结果(在Go Playground上尝试):

{1 Vanaraj [{10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj}]}

另外请注意,如果你事先知道迭代次数(在你的情况下是10),你可以事先创建一个足够大的切片,然后使用for ... range,只需将值分配给正确的元素,而无需调用append()。这样更高效:

book.Categories = make([]Category, 10)
for i := range book.Categories {
    book.Categories[i] = Category{
        Id:   10,
        Name: "Vanaraj",
    }
}
英文:

You are not appending anything to book.Categories, in each iteration of the for loop you always create a new slice with a composite literal and you assign it to book.Categories.

If you want to append values, use the builtin append() function:

for i := 0; i &lt; 10; i++ {
	book.Categories = append(book.Categories, Category{
		Id:   10,
		Name: &quot;Vanaraj&quot;,
	})
}

Output (try it on the Go Playground):

{1 Vanaraj [{10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj} {10 Vanaraj}]}

Also note that if you know the iteration count in advance (10 in your case), you can create a big-enough slice beforehand, you can use for ... range and just assign values to the proper element without calling append(). This is more efficient:

book.Categories = make([]Category, 10)
for i := range book.Categories {
	book.Categories[i] = Category{
		Id:   10,
		Name: &quot;Vanaraj&quot;,
	}
}

huangapple
  • 本文由 发表于 2015年12月17日 16:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/34329441.html
匿名

发表评论

匿名网友

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

确定