dictionary - 为什么count++(而不是count = count + 1)改变了Golang中map的返回方式

标签 dictionary go hashmap

我使用了一个映射,它使用句子中的单词作为键,使用整数作为值。

func WordCount(s string) map[string]int {
    var m map[string]int
    m = make(map[string]int)
    var substrings[]string
    count := 0
    substrings = strings.Split(s, " ")
    for i := range substrings {
        count = count + 1
        m[substrings[i]] = count
    }

    return m
}

func main() {   
    fmt.Println(WordCount("I am learning GO since some days"))
}

上面的代码总是以正确的顺序显示 map ,即

map[I:1 am:2 learning:3 GO:4 since:5 some:6 days:7]

但是如果我改变

count = count + 1

count++

输出变为:

map[learning:3 GO:4 since:5 some:6 days:7 I:1 am:2]

我知道 map 迭代在 Golang 中是随机的,但为什么 count = count + 1 总是导致 map 迭代以与 count++ 相反的有序方式返回?

最佳答案

更改 count 变量值的方式与 map 元素的迭代顺序无关。

没有“正确”的迭代顺序,迭代顺序可以被认为是随机的(在当前实现中它随机的)。引用自 language spec: For statements :

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

有关该主题的更多信息,请查看此答案:Why can't Go iterate maps in insertion order?

The Go Tour使用 Go Playground提供代码编辑器和运行器。 Go Playground 缓存您在其上运行的代码的输出。运行两次完全相同的代码只会显示缓存的输出。

但是,如果您更改了代码,那将被“视为”新代码,它将被编译和运行(其输出将在之后被缓存)。由于它是重新运行的,您可能会观察到一个新的随机顺序 - 您会这样做。

如果您再次更改代码中的某些内容,即使是添加或更改一些评论这样微不足道的内容,输出也会(可能)再次更改,请尝试一下。

有关如何实现 Playground 的更多信息,请参阅博客文章 Inside the Go Playground .

引用相关部分:

When the front end receives a compilation request it first checks memcache to see if it has cached the results of a previous compilation of that source. If found, it returns the cached response. The cache prevents popular programs such as those on the Go home page from overloading the back ends. If there is no cached response, the front end makes an RPC request to the back end, stores the response in memcache, parses the playback events, and returns a JSON object to the client as the HTTP response (as described above).

另请注意,以 Go 1.12 开头, map 在使用 fmt 包打印时被排序(以方便测试),因此现在打印同一张 map 将始终以相同的顺序列出元素。迭代顺序仍然故意保持不确定。

关于dictionary - 为什么count++(而不是count = count + 1)改变了Golang中map的返回方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966514/

相关文章:

python - 更新字典的键和值

go - 使用结构更新值

arrays - Perl 中的 HashMap

java - 添加和删​​除 ArrayList 中设置为 hashmap 中的值的元素

python - 字典中具有其他数据类型的 bool 键

python - 用未知键初始化一个大字典?还有比这更好的方法吗?

select - golang : goroute with select doesn't stop unless I added a fmt. 打印()

Java HashMap 自动值复制问题

python - 如何从多个 csv 文件创建数据帧字典

go - 按距离快速搜索数百万个坐标