30
loading...
This website collects cookies to deliver better user experience
reflect
package, I realized this is totally unnecessary. We can compare slices, maps, structs (anything!) simply by passing them into reflect.DeepEqual(x,y)
, which reports whether two variables are "deeply equal."func ReverseSlice(s []string) []string {
reversedSlice := make([]string, len(s))
for i, j := len(s), 0; i > 0; i, j = i-1, j+1 {
reversedSlice[j] = s[i-1]
}
return reversedSlice
}
func TestReverseSlice(t *testing.T) {
got := ReverseSlice([]string{
"person1",
"person2",
"person3",
"person4",
})
want := []string{
"person4",
"person3",
"person2",
"person1",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %q slice but expected %q", got, want)
}
}
Array values are deeply equal when their corresponding elements are deeply equal.
map[string]string
is going to be constructed with a potentially random order.DeepEqual
? They will both need to either be nil, or not nil, have the same length, and the same corresponding key/values. main()
to showcase a few of these points with print statements:func main() {
m1, m2 := make(map[string]string), make(map[string]string)
m1["person1"] = "person1"
m1["person2"] = "person2"
m2["person2"] = "person2"
m2["person1"] = "person1"
fmt.Printf("type=%T -- addr=%p -- len=%d\n", m1, &m1, len(m1))
fmt.Printf("type=%T -- addr=%p -- len=%d\n", m2, &m2, len(m2))
if reflect.DeepEqual(m1, m2) {
fmt.Println("they are equal")
} else {
fmt.Println("they are NOT equal")
}
}
nil
). type=map[string]string -- addr=0xc0000b0018 -- len=2
type=map[string]string -- addr=0xc0000b0020 -- len=2
they are equal