其他分享
首页 > 其他分享> > 返回随机问候语

返回随机问候语

作者:互联网

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

为了完成这事儿,你可以尝试用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))]
}

 这片代码中:

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!

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

  

标签:返回,name,切片,随机,问候语,go,message,hello,greetings
来源: https://www.cnblogs.com/yaoshi641/p/15239162.html