The example below shows how you'd print a particular field value of a struct:
type child struct {
name string
age int
}
type parent struct {
name string
age int
children child
}
func main() {
family := parent{
name: "John",
age: 40,
children: child{
name: "Johnny",
age: 10,
},
}
fmt.Println(family.children.name); // Prints "Johnny"
}
The code above would print "Johnny", which is a value of a struct within the parent struct. The code doesn't make much sense, however, because the field is children
, yet there is only ever able to be one child as its value.
Let's leverage slices. Now that we know how to print a particular value, all we would need for your case is to loop over a slice and print the same way we did above.
We can do that like this:
type child struct {
name string
age int
}
type parent struct {
name string
age int
children []child
}
func main() {
family := parent{
name: "John",
age: 40,
children: []child{
child{
name: "Johnny",
age: 10,
},
child{
name: "Jenna",
age: 7,
},
},
}
for _, child := range family.children {
fmt.Println(child.name);
}
}
The above example will pront "Johnny" and "Jenna".
You can use a similar pattern to what I showed above in your own code to loop through your structs and print whatever value your heart desires :)
Keep in mind, there are many ways to loop through things. For example, all the following loops would print "Johnny" and "Jenna" from the examples above.
for _, child:= range family.children{ // Prints "Jonny" and "Jenna"
fmt.Println(child.name);
}
for i, _ := range family.children{ // Prints "Jonny" and "Jenna"
fmt.Println(family.children[i].name);
}
for i := 0; i < len(family.children); i++ { // Prints "Jonny" and "Jenna"
fmt.Println(family.children[i].name);
}