From 0ed51a711ad0dcaf3eef5b1a5b20279c7f73300b Mon Sep 17 00:00:00 2001 From: Silentroar Date: Tue, 31 May 2022 09:54:09 +0800 Subject: [PATCH] fix(#38): add a guard for slices with length 0 When the slice's length is 0, should directly return to prevent false result or slice out of bounds runtime error --- ex4.5/unique.go | 4 ++++ ex4.5/unique_test.go | 21 ++++++++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/ex4.5/unique.go b/ex4.5/unique.go index d1ad75b..68eb6a5 100644 --- a/ex4.5/unique.go +++ b/ex4.5/unique.go @@ -2,6 +2,10 @@ package unique func unique(strs []string) []string { + if len(strs) == 0 { + return strs + } + w := 0 // index of last written string for _, s := range strs { if strs[w] == s { diff --git a/ex4.5/unique_test.go b/ex4.5/unique_test.go index f00064a..0c473bd 100644 --- a/ex4.5/unique_test.go +++ b/ex4.5/unique_test.go @@ -6,10 +6,21 @@ import ( ) func TestUnique(t *testing.T) { - s := []string{"a", "a", "b", "c", "c", "c", "d", "d", "e"} - got := unique(s) - want := []string{"a", "b", "c", "d", "e"} - if !reflect.DeepEqual(got, want) { - t.Errorf("got %v, want %v", got, want) + ss := [][]string{ + {"a", "a", "b", "c", "c", "c", "d", "d", "e"}, + {}, } + + want := [][]string{ + {"a", "b", "c", "d", "e"}, + {}, + } + + for i, s := range ss { + got := unique(s) + if !reflect.DeepEqual(got, want[i]) { + t.Errorf("got %v, want %v", got, want[i]) + } + } + }