2

I'm new to GO. There is the problem I'm facing.

The function takes a 2D array in arbitrary size as argument:

func PrintArray(a [][]string) {
    for _, v1 := range a {
        for _, v2 := range v1 {
            fmt.Printf("%s ", v2)
        }
        fmt.Printf("\n")
    }
}

As you can see, since the nested loop uses range. The size of the array really doesn't matter.

But when I try to call this function:

a := [3][2]string{
    {"line", "tiger"},
    {"cat", "dog"},
    {"pigeon", "hamster"},
}
PrintArray(a[:])

It complains about:

cannot use a[:] (type [][2]string) as type [][]string in argument to PrintArray

However, it won't compile with a[:][:] either.

What is the correct way to define a multidimensional array in arbitrary size in GO lang?

2 Answers 2

4

In Go, array types and slice types are distinct. Pass slices to slices.

For example,

package main

import (
    "fmt"
)

func main() {
    a := [][]string{
        {"line", "tiger"},
        {"cat", "dog"},
        {"pigeon", "hamster"},
    }
    PrintSlices(a)
}

func PrintSlices(a [][]string) {
    for _, v1 := range a {
        for _, v2 := range v1 {
            fmt.Printf("%s ", v2)
        }
        fmt.Printf("\n")
    }
}

Playground: https://play.golang.org/p/3mPDTIEUQmT

Output:

line tiger 
cat dog 
pigeon hamster

To allocate a matrix:

package main

import (
    "fmt"
)

func NewMatrix(rows, cols int) [][]int {
    m := make([][]int, rows)
    for r := range m {
        m[r] = make([]int, cols)
    }
    return m
}

func main() {
    m := NewMatrix(3, 2)
    fmt.Println(m)
}

Playground: https://play.golang.org/p/qvwQu2giRcP

Output:

[[0 0] [0 0] [0 0]]
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to define the size of inner array?
See my revised answer.
1

Interesting question. This should work

a := [][]string{
    {"line", "tiger"},
    {"cat", "dog"},
    {"pigeon", "hamster"},
}
PrintArray(a[:])

From the error messages, I would guess that arrays defined with size are of different types.

For example, if the PrintArray looks like this:

func PrintArray(a [3][2]string) {

Then you can pass it an array defined as:

a := [3][2]string.

If we vary the numbers in either the PrintArray method or a, so that they differ, we get an error message that says:

cannot use a (type [3][2]string) as type [3][1]string in argument to PrintArray

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.