返回随机问候语

在本节,你又要调整代码了,这将会返回预定义的问候语中的一条,代替原先只能返回固定问候

为了完成这事儿,你可以尝试用Go 切片,一个切片就相当于数组,不同之处在于添加或删除项目时切片的大小会动态改变.切片是Go语言中特别有用的类型之一

你将添加一个切片,其中包含三个问候语,然后你编码实现随机返回消息,想要知道更多关于切片的知识,请看看 go 切片

  1.在greetings/greetings.go中,做如下改造

package greetings

import (
    "errors"
    "fmt"
    "math/rand"
    "time"
)

// 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
}

// 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))]
}

 这片代码中:

  • 添加了 randomFormat函数 用来返回随机选择的问候函数,注意,randomFormat函数是小写字母开头,这表示,这个代码只能被自己包访问(换句话说,他不能被导出).
  • 在random中,声明了包含三个消息格式的 formats切片,在声明切片时,用[]string这样的方法,可以让你省去括号中的大小,这就告诉Go,切片下的数组尺寸是可以动态改变的
  • 使用math/rand包用来产生随机数,这样就能选切片中的项目了
  • init函数内,使用当前时间作为rand包的种子, Go会在程序启动时,自动执行init函数,之后,全局变量会被初始化,有关init函数的细节,请看"Go本质论"
  • hello中,调用random函数就会返回一个消息格式,然后使用格式和name值一起创造消息
  • 返回之前你做的那样的消息

2.对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)
}

3.在hello路径下,运行hello.go 来确认代码可以执行,运行多次,观察问候语的变化

$ go run .
Great to see you, Gladys!

$ go run .
Hi, Gladys. Welcome!

$ go run .
Hail, Gladys! Well met!

接下来,使用切片给多人发送问候

  

原文地址:https://www.cnblogs.com/yaoshi641/p/15239162.html