Home > Net >  golang: how to use make() function to generate 2-demensional slice?
golang: how to use make() function to generate 2-demensional slice?

Time:08-21

First I declared variable p in one place:

var p [2][]int

It's a 2d slice, and size of each dimension should be dynamically determined at run time.

Then in another function, I tried to initialize p:

    n1 := ...
    n2 := ...
    p = make([][]int, 2) // syntax error
    p[0] = make([]int, n1) // ok
    p[1] = make([]int, n2) // ok

The syntax error is:

cannot use make([][]int, 2) (value of type [][]int) as [2][]int value in assignment(compiler)

How to fix it? Thanks.

CodePudding user response:

The declaration of p here indicates a 2D array. You can convert it to a 2D Slice:

var p [][]int 

This should then work as expected when allocation is done via make().

  • Related