U
U
uvelichitel2020-01-31 18:48:45
go
uvelichitel, 2020-01-31 18:48:45

How to declare an array of arrays of arbitrary nesting?

I tried
type sl []sl
it compiles, and you can even construct

var foo sl = make(sl, 2)
var bar sl = make(sl, 0)
var bazz sl = make(sl, 2)
bazz[0] = foo
bazz[1] = bar
fmt.Println(bazz)
fmt.Println("size", unsafe.Sizeof(bazz))

prints
[[[] []] []]
size 12
but it is not clear how to declare the element type and how to fill...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2020-02-02
@uvelichitel

If you declare type s1 []s1, then fill it like this:

s1 := s1{
    {
      {}, {
        {}, {}, {}, {}, {},
      }, {},
    },
  }

This is of no use, really, because there is nowhere to store values.
If you just need to store an n-dimensional array, I would suggest that it is better to store a one-dimensional array, just write a function to access the desired element, taking into account n-dimensionality.
If you need multi-nesting and nested neighboring elements can have different dimensions, then you will have to make a structure so that you can store values.
type s1 struct {
  Value    int // тут любой тип можно, в принципе, лучше указателем
  Children []s1
}

func main() {
  s1 := s1{
    Children: []s1{
      {Children: []s1{
        {Value: 1}, {Value: 2}, {Value: 3},
      }},
      {Children: []s1{
        {Value: 4}, {Value: 5},
      }},
    },
  }
  fmt.Println(s1)
}

A
alfss, 2020-01-31
@alfss

https://tour.golang.org/concurrency/7

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question