/
greetings.go
52 lines (47 loc) · 1.45 KB
/
greetings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package greetings
import (
"errors"
"fmt"
"math/rand"
"time"
)
// Hello returns a greeting that embeds the name in the message
func Hello(name string) (string, error) {
//if no name was given, return an error with a message
if name == "" {
return "", errors.New("empty name")
}
// Use the fmt package's Sprintf function to create a greeting message.
// Sprintf substitutes the name parameter's value in the %v format verb.
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
// Hellos returns a map that associates each of the named people with a greeting message.
func Hellos(names []string) (map[string]string, error) {
// A map to associate names with messages
messages := make(map[string]string)
// loop through the received slices of names, calling the hello function to get a greetings message for each name
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
messages[name] = message
}
return messages, nil
}
// sets tnitial values for the variables used in the function
func init() {
// Random numbers are generated by a Source.
// Seed uses the provided seed value to initialize the default Source to a deterministic state.
rand.Seed(time.Now().UnixNano())
}
//returns a random greeting from the set of greetings
func randomFormat() string {
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
return formats[rand.Intn(len(formats))]
}