go - go 中 map 键循环的++ 运算符

标签 go

我在这里学习 Go 教程 https://tour.golang.org/moretypes/23并稍微修改了练习以尝试更深入地挖掘。

package main

import (
    "fmt"
    "strings"
)

func WordCount(s string) map[string]int {
    m := make(map[string]int)
    x := strings.Fields(s)
    for _, e := range x {
        m[e]++
    }

    return m
}

func main() {
    phrase := "The quick brown fox"
    fmt.Println(WordCount(phrase), "length:", len(WordCount(phrase)))
}

对我来说没有意义的是++ 运算符在向 map 添加新元素时在此上下文中的工作方式。

Definition of ++ operator: Increment operator. It increases the integer value by one.

在此上下文中,++ 运算符增加映射长度的整数值,然后将 e 元素添加到新的映射长度?

最佳答案

mapint 值的默认值为 0。因此,当您遍历 x 并调用 m[e]++ 时,扩展版本将是

m[e] = m[e] + 1

换句话说:

m[e] = 0 + 1

当然,如果某个字段重复,则它已经在 map 中(某些值 > 0)。

当您在循环后检查 map 的长度时,它会给出字符串中唯一字段的数量。

关于go - go 中 map 键循环的++ 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54224131/

相关文章:

google-app-engine - 在应用引擎模块之间共享数据

performance - Go 语言指针性能

api - 未在Vue页面上检测到Cookie

mongodb - 无法从 MongoDB 中解码 ObjectId SubValue 结果在 Golang 中

http - 如何在Go中请求具有特定字符集的页面?

sockets - 去写套接字 - 无效参数

curl - Golang 中的函数基础

mysql - 如何从 MySQL 中选择数据然后将其附加到新结构并将其转换为字节

eclipse - 如何让自动完成 (GoCode) 与我的所有导入一起使用?

arrays - 将结构数组转换为字符串数组以显示为表格