From 8ed06b4d9d0a980d9bfc528314e4d3203e9f4679 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 2 Mar 2024 16:01:00 -0500 Subject: [PATCH] Initial array slices --- learn_go_with_tests/arrays/go.mod | 3 ++ learn_go_with_tests/arrays/sum.go | 23 ++++++++++++++++ learn_go_with_tests/arrays/sum_test.go | 38 ++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 learn_go_with_tests/arrays/go.mod create mode 100644 learn_go_with_tests/arrays/sum.go create mode 100644 learn_go_with_tests/arrays/sum_test.go diff --git a/learn_go_with_tests/arrays/go.mod b/learn_go_with_tests/arrays/go.mod new file mode 100644 index 0000000..88bf4e7 --- /dev/null +++ b/learn_go_with_tests/arrays/go.mod @@ -0,0 +1,3 @@ +module myarray + +go 1.21.0 diff --git a/learn_go_with_tests/arrays/sum.go b/learn_go_with_tests/arrays/sum.go new file mode 100644 index 0000000..710c016 --- /dev/null +++ b/learn_go_with_tests/arrays/sum.go @@ -0,0 +1,23 @@ +package arrays + +func Sum(a []int) int { + sum := 0 + + //aternatively + // for i := 0; i < 5; i++ { + // sum += a[i] + // } + + // OR + + // for i := range a { + // sum += a[i] + // } + + // OR + + for _, v := range a { + sum += v + } + return sum +} diff --git a/learn_go_with_tests/arrays/sum_test.go b/learn_go_with_tests/arrays/sum_test.go new file mode 100644 index 0000000..db0aac2 --- /dev/null +++ b/learn_go_with_tests/arrays/sum_test.go @@ -0,0 +1,38 @@ +package arrays + +import "testing" + +// go test -cover will show the test coverage for our package. + +func TestSum(t *testing.T) { + + t.Run("sum collection of 5 of integers", func(t *testing.T) { + numbers := []int{1, 2, 3, 4, 5} + + got := Sum(numbers) + expected := 15 + + // https://pkg.go.dev/fmt + if got != expected { + t.Errorf("got %d expected %d given, %v", got, expected, numbers) + } + }) + + // go test -cover will show the test coverage for our package. + + // You can see that commenting out this "duplicate" function still retains 100% + // test coverage, which is how we know it's redundant. + + // t.Run("sum a collection of any size", func(t *testing.T) { + // numbers := []int{1, 2, 3} + + // got := Sum(numbers) + // expected := 6 + + // // https://pkg.go.dev/fmt + // if got != expected { + // t.Errorf("got %d expected %d given, %v", got, expected, numbers) + // } + // }) + +}