如何使用 Golang 函数遍历映射?

如何遍历 golang 映射?可以使用以下方法遍历 golang 映射的元素:foreach() 函数:提供键和值处理函数作为参数。range 语句:迭代映射中的键和值。实战案例:计算映射中值的总和遍历映射中的值。将每个值累加到总和变量中。

如何使用 Golang 函数遍历映射?

如何使用 Golang 函数遍历映射

映射是 Golang 中一种存储键值对的数据结构。我们可以通过使用内置函数遍历映射中的元素。

forEach() 函数

最常用的遍历函数是 forEach(), 它接受两个函数作为参数:一个键函数和一个值函数。

func main() {
    m := map[string]int{"one": 1, "two": 2, "three": 3}

    forEach(m, func(key string) {
        fmt.Println("Key:", key)
    }, func(value int) {
        fmt.Println("Value:", value)
    })
}

func forEach(m map[string]int, keyFunc func(string), valueFunc func(int)) {
    for k, v := range m {
        keyFunc(k)
        valueFunc(v)
    }
}

输出:

Key: one
Value: 1
Key: two
Value: 2
Key: three
Value: 3

range 语句

range 语句也是遍历映射的一种简单方法。它将映射中的键和值作为两个独立的变量。

func main() {
    m := map[string]int{"one": 1, "two": 2, "three": 3}

    for key, value := range m {
        fmt.Println("Key:", key, "Value:", value)
    }
}

输出相同:

Key: one Value: 1
Key: two Value: 2
Key: three Value: 3

实战案例:计算映射中值的总和

遍历映射的一个常见用法是计算映射中值的总和。

func main() {
    m := map[string]int{"one": 1, "two": 2, "three": 3}

    sum := 0
    forEach(m, func(key string) {}, func(value int) {
        sum += value
    })

    fmt.Println("Total sum:", sum)
}

输出:

Total sum: 6

以上就是如何使用 Golang 函数遍历映射?的详细内容,更多请关注www.sxiaw.com其它相关文章!