golang: using nested structs

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

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}

我该如何将st放入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}}

在此处进行测试:点击这里

在继续您的项目之前,强烈建议您阅读以下内容:

英文:

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:

huangapple
  • 本文由 发表于 2014年9月5日 17:51:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/25683122.html
匿名

发表评论

匿名网友

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

确定