ランダムな挨拶を返す

このセクションでは、毎回単一の挨拶を返すのではなく、定義済みの複数の挨拶メッセージの中から1つを返すようにコードを変更します。

これを行うために、Goのスライスを使用します。スライスは配列のようなものですが、アイテムを追加および削除するとサイズが動的に変化します。スライスはGoの最も便利な型の1つです。

3つの挨拶メッセージを含む小さなスライスを追加し、コードがメッセージの1つをランダムに返すようにします。スライスの詳細については、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では、3つのメッセージ形式を持つformatsスライスを宣言します。スライスを宣言するときは、サイズを角括弧で省略します。例えば、[]stringのように。これは、Goに対して、スライスの基盤となる配列のサイズを動的に変更できることを伝えます。
    • スライスからアイテムを選択するための乱数を生成するために、math/randパッケージを使用します。
    • Helloでは、randomFormat関数を呼び出して、返信するメッセージの形式を取得し、次にその形式とname値を組み合わせてメッセージを作成します。
    • 前と同じように、メッセージ(またはエラー)を返します。
  2. hello/hello.goで、コードを次のように変更します。

    hello.goのHello関数呼び出しに、Gladysの名前(または別の名前でもかまいません)を引数として追加するだけです。

    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!
    

次に、スライスを使用して複数の人に挨拶をします。