如何在golang中比较两个[] []字符串数组

func assertEq(test [][]string, ans [][]string) {
    for i := 0; i < len(test); i++ {
        for j := 0; j < len(ans); j++ {
            if test[i][j] != ans[i][j] {
                fmt.Print(test)
                fmt.Print(" ! ")
                fmt.Print(ans)
            }
        }
    }
    fmt.Println()
}

In my code it's not checking. I have used two different string arrays to compare each and every character.

i and j are lengths of test and ans. So, they are not valid index for test[i][j] or ans[i][j].

You can simply use reflect.DeepEqual().

You can extend this solution for multiple dimension slices.

One simple example:

package main

import (
    "fmt"
    "reflect"
)

func assertEq(test [][]string, ans [][]string) bool {
    return reflect.DeepEqual(test, ans)
}

func main() {
    str1 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2", "3"}}
    str2 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2", "3"}}
    str3 := [][]string{{"1", "2", "3"}, {"1", "2", "3"}, {"1", "2"}}

    fmt.Println(assertEq(str1, str2)) // answer is true
    fmt.Println(assertEq(str1, str3)) // answer is false
}

package cmp

import "github.com/google/go-cmp/cmp"

Package cmp determines equality of values.

This package is intended to be a more powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal.


Use package cmp.