简体   繁体   中英

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

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM