You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Go has a built-in function `delete` that works on maps. It takes two arguments. The first is the map and the second is the key to be removed.
634
+
Go has a built-in function `delete` that works on maps. It takes two arguments and returns nothing. The first argument is the map and the second is the key to be removed.
635
635
636
-
The `delete` function returns nothing, and we based our `Delete` method on the same notion. Since deleting a value that's not there has no effect, unlike our `Update` and `Add` methods, we don't need to complicate the API with errors.
636
+
## Refactor
637
+
There isn't much to refactor, but we can implement the same logic from `Update` to handle cases where word doesn't exist.
638
+
639
+
```go
640
+
funcTestDelete(t *testing.T) {
641
+
t.Run("existing word", func(t *testing.T) {
642
+
word:="test"
643
+
dictionary:= Dictionary{word: "test definition"}
644
+
645
+
err:= dictionary.Delete(word)
646
+
647
+
assertError(t, err, nil)
648
+
649
+
_, err = dictionary.Search(word)
650
+
651
+
assertError(t, err, ErrNotFound)
652
+
})
653
+
654
+
t.Run("non-existing word", func(t *testing.T) {
655
+
word:="test"
656
+
dictionary:= Dictionary{}
657
+
658
+
err:= dictionary.Delete(word)
659
+
660
+
assertError(t, err, ErrWordDoesNotExist)
661
+
})
662
+
}
663
+
```
664
+
665
+
## Try to run test
666
+
667
+
The compiler will fail because we are not returning a value for `Delete`.
668
+
669
+
```
670
+
./dictionary_test.go:77:10: dictionary.Delete(word) (no value) used as value
671
+
./dictionary_test.go:90:10: dictionary.Delete(word) (no value) used as value
672
+
```
673
+
674
+
## Write enough code to make it pass
675
+
676
+
```go
677
+
func(dDictionary) Delete(wordstring) error {
678
+
_, err:= d.Search(word)
679
+
680
+
switch err {
681
+
case ErrNotFound:
682
+
return ErrWordDoesNotExist
683
+
casenil:
684
+
delete(d, word)
685
+
default:
686
+
return err
687
+
}
688
+
689
+
returnnil
690
+
}
691
+
```
692
+
693
+
We are again using a switch statement to match on the error when we attempt to delete a word that doesn't exist.
0 commit comments