如何将对象附加到切片中?

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

How to append objects to a slice?

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习golang,我想将查询结果聚合到一个名为results的切片中,然后将其推送到浏览器。以下是代码:

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{} // 这里是问题所在

    for iter.Next(&result) {
        results = append(results, Cats{category: 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)    
}

但是我得到了以下错误信息:

类型[]Cats不是一个表达式

我该如何修复这个问题?

英文:

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?

答案1

得分: 5

你可以这样说:

results := make([]Cats, 0)

或者

var results []Cats

或者

results := []Cats{}
英文:

You can say

results := make([]Cats, 0)

or

var results []Cats

or

results := []Cats{}

instead.

答案2

得分: 2

你可以使用results := make([]Cats, len),其中len是切片的初始长度。

results := []Cats{}也可以工作。

如果你使用var results []Cats,它的初始值是nil,所以在使用append之前需要初始化它。

英文:

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.

huangapple
  • 本文由 发表于 2016年4月20日 08:34:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/36731805.html
匿名

发表评论

匿名网友

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

确定