how to create array of structures instances for the nested structures

118 views
Skip to first unread message

Nagaraj Trivedi

unread,
Jul 14, 2021, 11:32:13 AM7/14/21
to golang-nuts
Hi all, it would be helpful for me if a small doubt of mine is resolved.

I want to know how to create an array of structure instances  for a nested structure. Let me write it

type Strct1 struct {
    val1 int
     val2 int
}
type Strct2 struct {
     Namce string
      temp     Strct1
}
I want to create an array of instances for Strct2 and initialise it. Please let me know how to do it.

Thanks
Nagaraj
     
     

Brian Candler

unread,
Jul 14, 2021, 1:59:21 PM7/14/21
to golang-nuts
https://play.golang.org/p/YtxPYZ4H-Sy

In practice, you'll usually find you want to create a slice, not an array.  Arrays have a fixed size.

jake...@gmail.com

unread,
Jul 14, 2021, 2:03:36 PM7/14/21
to golang-nuts
Some ways to do it:


Note that arrays are rarely used in Go. When in doubt, default to using a slice. I provided  slice examples as well.
If you want to initialize a very large array or slice to a value other than the zero value, you could also use a loop.

Reply all
Reply to author
Forward
0 new messages