Karlom
Karlom

Reputation: 14884

How to append objects to a slice?

I am new to golang and I'd like to aggregaet query results into a results slice to be pushed to the browser. Here is the code:

type Category struct {
    Id          bson.ObjectId `bson:"_id,omitempty"`
    Name        string
    Description string
    Tasks       []Task
}


type Cats struct {
    category Category
} 

func CategoriesCtrl(w http.ResponseWriter, req *http.Request) {
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    c := session.DB("taskdb").C("categories")

    iter := c.Find(nil).Iter()
    result := Category{}
    results := []Cats //Here is the problem

    for iter.Next(&result) {
        results = append(results, result)
        fmt.Printf("Category:%s, Description:%s\n", result.Name, result.Description)
        tasks := result.Tasks
        for _, v := range tasks {
            fmt.Printf("Task:%s Due:%v\n", v.Description, v.Due)
        }
    }
    if err = iter.Close(); err != nil {
        log.Fatal(err)
    }
    fmt.Fprint(w, results)    
}

But instead I get

type []Cats is not an expression

How can I fix this?

Upvotes: 1

Views: 1989

Answers (2)

Ken Bloom
Ken Bloom

Reputation: 58810

You can say

results := make([]Cats, 0)

or

var results []Cats

or

results := []Cats{}

instead.

Upvotes: 5

simon_xia
simon_xia

Reputation: 2544

You can use results := make([]Cats, len) instead, where len is the initial length of slice.

results := []Cats{} will also work.

If you use var results []Cats, its initial value is nil so you'd need to initialize it before using append.

Upvotes: 2

Related Questions