返回随机问候语
在本节中,您将修改代码,使其不再每次都返回一个问候语,而是从几个预定义的问候消息中返回一个。
为此,您将使用 Go 切片。切片类似于数组,但其大小会随着您添加和删除项而动态改变。切片是 Go 最有用的类型之一。
您将添加一个小型切片来包含三个问候消息,然后让您的代码随机返回其中一条消息。有关切片的更多信息,请参阅 Go 博客中的 Go 切片。
- 在 greetings/greetings.go 中,将您的代码更改为如下所示。
package greetings import ( "errors" "fmt" "math/rand" ) // Hello returns a greeting for the named person. func Hello(name string) (string, error) { // If no name was given, return an error with a message. if name == "" { return name, errors.New("empty name") } // Create a message using a random format. message := fmt.Sprintf(randomFormat(), name) return message, nil } // 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))] }
在此代码中,您
- 添加一个
randomFormat
函数,该函数返回一个随机选择的问候消息格式。请注意,randomFormat
以小写字母开头,使其只能被其自身包中的代码访问(换句话说,它未导出)。 - 在
randomFormat
中,声明一个包含三个消息格式的formats
切片。声明切片时,请在方括号中省略其大小,如下所示:[]string
。这告诉 Go 底层数组的大小可以动态更改。 - 使用
math/rand
包 来生成一个随机数,用于从切片中选择一个项。 - 在
Hello
中,调用randomFormat
函数以获取要返回的消息的格式,然后将格式和name
值组合起来创建消息。 - 像以前一样返回消息(或错误)。
- 添加一个
- 在 hello/hello.go 中,将您的代码更改为如下所示。
您只是将 Gladys 的名字(或者您喜欢的其他名字)作为参数添加到 hello.go 中的
Hello
函数调用中。package main import ( "fmt" "log" "example.com/greetings" ) func main() { // Set properties of the predefined Logger, including // the log entry prefix and a flag to disable printing // the time, source file, and line number. log.SetPrefix("greetings: ") log.SetFlags(0) // Request a greeting message. message, err := greetings.Hello("Gladys") // If an error was returned, print it to the console and // exit the program. if err != nil { log.Fatal(err) } // If no error was returned, print the returned message // to the console. fmt.Println(message) }
- 在命令行中,位于 hello 目录中,运行 hello.go 以确认代码正常工作。多次运行它,注意问候语会发生变化。
$ go run . Great to see you, Gladys! $ go run . Hi, Gladys. Welcome! $ go run . Hail, Gladys! Well met!
接下来,您将使用切片来问候多个人。