Go 语言学习系列(五): map

改造 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
}

// Hellos returns a map that associates each of the named people
// with a greeting message.
func Hellos(names []string) (map[string]string, error) {
    // A map to associate names with messages.
    messages := make(map[string]string)
    // Loop through the received slice of names, calling
    // the Hello function to get a message for each name.
    for _, name := range names {
        message, err := Hello(name)
        if err != nil {
            return nil, err
        }
        // In the map, associate the retrieved message with
        // the name.
        messages[name] = message
    }
    return messages, 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 one of the message formats selected at random.
    return formats[rand.Intn(len(formats))]
}

从上面简单的代码中可以看到 Map 类似于一个词典, 相当于 c# 里面的 dictionary. 如果你希望了解更多的 map 的用法, 可以通过这个链接: https://blog.golang.org/maps
咱们这里记住怎么初始化一个 map:

messages := make(map[string]string)

这就是语法, 记住就行.

然后修改调用函数, 在 hello.go 文件:

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)

    // A slice of names.
    names := []string{"Gladys", "Samantha", "Darrin"}

    // Request greeting messages for the names.
    messages, err := greetings.Hellos(names)
    if err != nil {
        log.Fatal(err)
    }
    // If no error was returned, print the returned map of
    // messages to the console.
    fmt.Println(messages)
}

这段代码更加简单了, 声明一个 slice 数组, 然后将这个数组传过去. 运行一下:

现在咱们学完了 slice, map, 也写了两个函数, main 和 hello(s), 下面该学学怎么写 test, 保证咱们的代码质量.

posted @ 2022-09-23 21:30  YanyuWu  阅读(6)  评论(0编辑  收藏  举报