英文:
golang: using nested structs
问题
我有两个结构体:
type person struct {
name string
age int
}
type class struct {
students []person
}
假设在main
函数中,我创建并填充了两个person
变量,然后我想将它们添加到一个类型为class
的变量中。我该如何做呢?
例如:
s := person{name: "Sean", age: 50}
t := person{name: "Nicola", age: 35}
我该如何将s
和t
放入lab := class
中?
英文:
I have two structs:
type person struct {
name string
age int
}
type class struct {
students []person
}
Lets say that in the main function, I create and populate two person variables and then I want to add them to a variable with class type. How can I do it?
I.e.
s := person{name: "Sean", age: 50}
t := person{name: "Nicola", age: 35}
how I can put s and t into:
lab:=class
?
答案1
得分: 4
以下是您要翻译的内容:
以下代码应该可以实现您想要的功能:
lab := class{[]person{s, t}}
在此处进行测试:点击这里。
在继续您的项目之前,强烈建议您阅读以下内容:
-
http://tour.golang.org/(正如Volker在评论中提到的)
英文:
The following should achieve what you want:
lab := class{[]person{s, t}}
Test it here.
Before you continue working on your project it's strongly recommended you read the following:
-
http://tour.golang.org/ (As Volker pointed out before me in the comments)
-
http://golang.org/doc/effective_go.html (After finishing the tour)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论