查找go中2D切片的长度

I want to check if the matrices are of the same size: if both matrices have the same number of rows and the same number of columns.

matrix1 := [][]int{{1,2,3} ,{4,5,6}}
matrix2 := [][]int{{7,8,9}, {10,11,12}}

I get len(matrix1) == len(matrix2) == 2. Which is the correct number of rows.

How can I check the length of each row (i.e. the number of columns, which should be 3) if I'm declaring the matrices as shown above?

Note that since every "row" in a 2D slice may have arbitrary length, you should check the length of each of the corresponding rows (having the same index) if they are equal.

Here's a function that does that:

func match(m1, m2 [][]int) bool {
    if len(m1) != len(m2) {
        return false
    }

    for i, row1 := range m1 {
        row2 := m2[i]
        if len(row1) != len(row2) {
            return false
        }
    }

    return true
}

See usage examples:

m1 := [][]int{{1, 2, 3}, {4, 5, 6}}
m2 := [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match(m1, m2))

m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12, 13}}
fmt.Println(match(m1, m2))

m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
fmt.Println(match(m1, m2))

m1 = [][]int{{1, 2, 3}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
fmt.Println(match(m1, m2))

Output (as expected):

true
true
false
false

Simplification for Special case:

If you have guarantee that in all of your matrices all rows have the same length, you can make a big simplification: in this case if number of rows matches, it's enough to compare the length of one of the rows only from each matrices, practically the first row.

It could look like this:

func match2(m1, m2 [][]int) bool {
    if len(m1) != len(m2) {
        return false
    }
    return len(m1) == 0 || len(m1[0]) == len(m2[0])
}

Testing it:

m1 = [][]int{{1, 2, 3}, {4, 5, 6}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match2(m1, m2))

m1 = [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
fmt.Println(match2(m1, m2))

Output:

true
false

Try these on the Go Playground.