Why Does the Assignment Order of Map Keys Affect Output in Go?
Given the Go code:
package main import "fmt" type Vertex struct { Lat, Long float64 } var m map[string]Vertex func main() { m = make(map[string]Vertex) m["Bell Labs"] = Vertex{ 40.68433, 74.39967, } m["test"] = Vertex{ 12.0, 100, } fmt.Println(m["Bell Labs"]) fmt.Println(m) }
When we run this code, it will output:
{40.68433 74.39967} map[Bell Labs:{40.68433 74.39967} test:{12 100}]
However, if we move the right curly brace in the test vertex declaration four spaces to the left, the output will change to:
{40.68433 74.39967} map[test:{12 100} Bell Labs:{40.68433 74.39967}]
This seemingly minor modification affects the order of the map keys in the output because the map "order" is dependent on the hash function used. Go uses a randomized hash function to prevent denial of service attacks based on hash collisions. Consequently, the map's order is not guaranteed, and modifications to the key-value pairs can alter that order.
Go's specification defines a map as an unordered group of elements with unique keys. It provides no guarantee of a specific order. This design allows for optimizations that could potentially change the order of map keys without any modification from the user's code. As a result, it is unwise to rely on the order of map keys in your applications.
The above is the detailed content of Why Does Changing the Formatting of a Go Map\'s Value Affect the Output Order of its Keys?. For more information, please follow other related articles on the PHP Chinese website!