📘

golang やってみた(4)

2023/02/26に公開

Return a random greeting

greegings.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, retur 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))]
}

次にhello.goを編集します

package main

import (
  "fmt"
  "log"

  "example.com/greetings"
)

func main() {
  // Set properties of the prodefined Logger, includint
  // 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)
}

連続して実行してみる

go run .
Great to see you, Gladys!
go run .
Great to see you, Gladys!
go run .
Hi, Gladys. Welcome!
go run .
Hi, Gladys. Welcome!
go run .
Hi, Gladys. Welcome!
go run .
Hi, Gladys. Welcome!
go run .
Hail, Gladys! Well met!
go run .
Great to see you, Gladys!
go run .
Great to see you, Gladys!
GitHubで編集を提案

Discussion