返回隨機問候語

在本節中,您將修改程式碼,使其不再每次都返回一個問候語,而是從幾個預定義的問候訊息中返回一個。

為此,您將使用 Go 切片。切片類似於陣列,但其大小會隨著您新增和刪除項而動態改變。切片是 Go 最有用的型別之一。

您將新增一個小型切片來包含三個問候訊息,然後讓您的程式碼隨機返回其中一條訊息。有關切片的更多資訊,請參閱 Go 部落格中的 Go 切片

  1. 在 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 值組合起來建立訊息。
    • 像以前一樣返回訊息(或錯誤)。
  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!
    

接下來,您將使用切片來問候多個人。