Return greetings for multiple people
In the last changes you'll make to your module's code, you'll add support for getting greetings for multiple people in one request. In other words, you'll handle a multiple-value input, then pair values in that input with a multiple-value output. To do this, you'll need to pass a set of names to a function that can return a greeting for each of them.
Note: This topic is part of a multi-part tutorial that begins with Create a Go module.
But there's a hitch. Changing the Hello function's parameter from a single name to a set of names would change the function's signature. If you had already published the example.com/greetings module and users had already written code calling Hello, that change would break their programs.
In this situation, a better choice is to write a new function with a different name. The new function will take multiple parameters. That preserves the old function for backward compatibility.
Steps
- Update your
greetings/greetings.gofile with the following code:
In this code, you:
- Add a
Hellosfunction whose parameter is a slice of names rather than a single name. Also, you change one of its return types from astringto amapso you can return names mapped to greeting messages. - Have the new
Hellosfunction call the existingHellofunction. This helps reduce duplication while also leaving both functions in place. - Create a
messagesmap to associate each of the received names (as a key) with a generated message (as a value). In Go, you initialize a map with the following syntax:make(map[key-type]value-type). You have theHellosfunction return this map to the caller. For more about maps, see Go maps in action on the Go blog. - Loop through the names your function received, checking that each has a non-empty value, then associate a message with each. In this
forloop,rangereturns two values: the index of the current item in the loop and a copy of the item's value. You don't need the index, so you use the Go blank identifier (an underscore) to ignore it. For more, see The blank identifier in Effective Go.
- Update your
hello/hello.gofile to pass a slice of names and print the contents of the names/messages map you get back:
With these changes, you:
- Create a
namesvariable as a slice type holding three names. - Pass the
namesvariable as the argument to theHellosfunction.
- Run the code from the command line to verify it works:
The output should be a string representation of the map associating names with messages, something like the following:
Summary
This topic introduced maps for representing name/value pairs. It also introduced the idea of preserving backward compatibility by implementing a new function for new or changed functionality in a module. For more about backward compatibility, see Keeping your modules compatible.
Next, you'll use built-in Go features to create a unit test for your code.