Return a random greeting
Note: This topic is part of a multi-part tutorial that begins with Create a Go module.
In this section, you'll change your code so that instead of returning a single greeting every time, it returns one of several predefined greeting messages.
To do this, you'll use a Go slice. A slice is like an array, except that its size changes dynamically as you add and remove items. The slice is one of Go's most useful types.
You'll add a small slice to contain three greeting messages, then have your code return one of the messages randomly. For more on slices, see Go slices in the Go blog.
Steps
1. Modify greetings/greetings.go to return a random greeting
In greetings/greetings.go, change your code so it looks like the following.
In this code, you:
- Add a
randomFormatfunction that returns a randomly selected format for a greeting message. Note thatrandomFormatstarts with a lowercase letter, making it accessible only to code in its own package (in other words, it's not exported). - In
randomFormat, declare aformatsslice with three message formats. When declaring a slice, you omit its size in the brackets, like this:[]string. This tells Go that the size of the array underlying the slice can be dynamically changed. - Use the
math/randpackage to generate a random number for selecting an item from the slice. - In
Hello, call therandomFormatfunction to get a format for the message you'll return, then use the format andnamevalue together to create the message. - Return the message (or an error) as you did before.
2. Update hello/hello.go to use the name "Gladys"
In hello/hello.go, change your code so it looks like the following.
You're just adding Gladys's name (or a different name, if you like) as an argument to the Hello function call in hello.go.
3. Run hello.go to confirm that the code works
At the command line, in the hello directory, run hello.go to confirm that the code works. Run it multiple times, noticing that the greeting changes.
Conclusion
Next, you'll use a slice to greet multiple people.