傳回隨機問候語

在本節中,您將變更程式碼,使其不再每次都傳回單一問候語,而是傳回多個預先定義的問候語訊息之一。

為此,您將使用 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!
    

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