英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论