random
This commit is contained in:
parent
ee2e28c11d
commit
173a1a39ec
23
greetings.go
23
greetings.go
|
|
@ -2,6 +2,8 @@ package greetings
|
|||
|
||||
import "fmt"
|
||||
import "errors"
|
||||
import "math/rand"
|
||||
import "time"
|
||||
|
||||
// Hello returns a greeting for the named person.
|
||||
func Hello(name string) (string,error) {
|
||||
|
|
@ -10,8 +12,27 @@ func Hello(name string) (string,error) {
|
|||
return "", errors.New("empty name")
|
||||
}
|
||||
// Return a greeting that embeds the name in a message.
|
||||
message := fmt.Sprintf("Hi, %v. Welcome!", name)
|
||||
message := fmt.Sprintf(randomFormat(), name)
|
||||
# message := fmt.Sprintf("Hi, %v. Welcome!", name)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// init sets initial values for variables used in the function.
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
// randomFormat returns one of a set of greeting messages. The returned
|
||||
// message is selected at random.
|
||||
func randomFormat() string {
|
||||
// A slice of message formats.
|
||||
formats := []string{
|
||||
"Hi, %v. Welcome!",
|
||||
"Great to see you, %v!",
|
||||
"Hail, %v! Well met!",
|
||||
}
|
||||
|
||||
// Return a randomly selected message format by specifying
|
||||
// a random index for the slice of formats.
|
||||
return formats[rand.Intn(len(formats))]
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue