6

This is my code:

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 = []Category{
            {
                Id : 10,
                Name : "Vanaraj",
            },
        }
    }

    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 Answer 1

18

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 < 10; i++ {
    book.Categories = append(book.Categories, Category{
        Id:   10,
        Name: "Vanaraj",
    })
}

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: "Vanaraj",
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ty sir, i got the same problem and this solution solved

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.