From 7a95cd68f173bbbeb51c18395990a3921c93ae73 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 2 Mar 2024 16:18:12 -0500 Subject: [PATCH] Comparison of slices --- learn_go_with_tests/arrays/sum.go | 8 +++++ learn_go_with_tests/arrays/sum_test.go | 47 +++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/learn_go_with_tests/arrays/sum.go b/learn_go_with_tests/arrays/sum.go index 710c016..2bd2ec5 100644 --- a/learn_go_with_tests/arrays/sum.go +++ b/learn_go_with_tests/arrays/sum.go @@ -21,3 +21,11 @@ func Sum(a []int) int { } return sum } + +// The ... in the method signature means it's variadic function +// meaning it takes a variable number of arguments + +// SumAll +func SumAll(numbersToSum ...[]int) []int { + return nil +} diff --git a/learn_go_with_tests/arrays/sum_test.go b/learn_go_with_tests/arrays/sum_test.go index db0aac2..3ead916 100644 --- a/learn_go_with_tests/arrays/sum_test.go +++ b/learn_go_with_tests/arrays/sum_test.go @@ -1,6 +1,10 @@ package arrays -import "testing" +import ( + "reflect" + "slices" + "testing" +) // go test -cover will show the test coverage for our package. @@ -36,3 +40,44 @@ func TestSum(t *testing.T) { // }) } + +func TestSumAll(t *testing.T) { + + got := SumAll([]int{1, 2}, []int{0, 9}) + expected := []int{3, 9} + + // can't compare slices...slices can only be compared to nil + // if got != expected { + // t.Errorf("got %v expected %v given", got, expected) + // } + + // https://pkg.go.dev/reflect#DeepEqual standard lib to the rescue + + // It's important to note that reflect.DeepEqual is not "type safe" + // - the code will compile even if you did something a bit silly. + // To see this in action, temporarily change the test to: + + // func TestSumAll(t *testing.T) { + + // got := SumAll([]int{1, 2}, []int{0, 9}) + // want := "bob" + + // if !reflect.DeepEqual(got, want) { + // t.Errorf("got %v want %v", got, want) + // } + // } + + if !reflect.DeepEqual(got, expected) { + t.Errorf("Using reflect.DeepEqual got %v expected %v given", got, expected) + } + + // From Go 1.21, slices standard package is available, which has a + // slices.Equal function to do a simple shallow compare on slices, + // where you don't need to worry about the types like the above case. + // Note that this function expects the elements to be comparable + // So, it can't be applied to slices with non-comparable elements like 2D slices. + + if !slices.Equal(got, expected) { + t.Errorf("Using slices.Equal got %v expected %v given", got, expected) + } +}