keyas the word and the
valueas the definition. And what better way is there to learn about Maps than to build our own dictionary?
mapkeyword and requires two types. The first is the key type, which is written inside the
. The second is the value type, which goes right after the
go testthe compiler will fail with
./dictionary_test.go:8:9: undefined: Search.
dictionary_test.go:12: got '' want 'this is just a test' given, 'test'.
assertStringshelper to make the implementation more general.
Dictionarytype, which we have not defined yet. Then called
Dictionarytype which acts as a thin wrapper around
map. With the custom type defined, we can create the
Errors can be converted to a string with the
.Error()method, which we do when passing it to the assertion. We are also protecting
ifto ensure we don't call
dictionary_test.go:22: expected to get an error.
Searchfunction by extracting it into a variable. This will also allow us to have a better test.
ErrNotFoundvariable so our test doesn't fail if we change the error text in the future.
Searchfunction to make the validation of the dictionary a little easier.
A map value is a pointer to a runtime.hmap structure.
makekeyword to create a map for you:
hash mapand point
dictionaryat it. Which ensures that you will never get a runtime panic.
Addis looking good. Except, we didn't consider what happens when the value we are trying to add already exists!
Addshould not modify existing values. It should only add new words to our dictionary.
Addto return an error, which we are validating against a new error variable,
ErrWordExists. We also modified the previous test to check for a
nilerror, as well as the
switchstatement to match on the error. Having a
switchlike this provides an extra safety net, in case
Searchreturns an error other than
DictionaryErrtype which implements the
errorinterface. You can read more about the details in this excellent article by Dave Cheney. Simply put, it makes the errors more reusable and immutable.
Updatethe definition of a word.
Updateis very closely related to
Addand will be our next implementation.
Add. So let's implement something really similar to
Add. If we pass in a new word,
Updatewill add it to the dictionary.
Updateto return an
Addexcept we switched when we update the
dictionaryand when we return an error.
ErrNotFoundand not add a new error. However, it is often better to have a precise error for when an update fails.
You can redirect the user when
ErrNotFoundis encountered, but display an error message when
Deletea word in the dictionary.
Dictionarywith a word and then checks if the word has been removed.
go testwe get:
deletethat works on maps. It takes two arguments. The first is the map and the second is the key to be removed.
deletefunction returns nothing, and we based our
Deletemethod on the same notion. Since deleting a value that's not there has no effect, unlike our
Addmethods, we don't need to complicate the API with errors.