Assignment Order in Go Maps
Considering the following 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) }
It outputs:
{40.68433 74.39967} map[Bell Labs:{40.68433 74.39967} test:{12 100}]
Modifying the test vertex declaration by moving the right "}" 4 spaces, as follows:
m["test"] = Vertex{ 12.0, 100, }
Changes the output to:
{40.68433 74.39967} map[test:{12 100} Bell Labs:{40.68433 74.39967}]
Explanation:
Map "order" in Go depends on the randomized hash function used to prevent denial of service attacks. As per the Go issue tracker (http://code.google.com/p/go/issues/detail?id=2630), map order is not guaranteed according to the specification.
According to the specification, a map is an unordered group of elements with unique keys. A future implementation could change the order of a map without modifying it in your code. Therefore, relying on specific map order is not a recommended practice in Go.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3