Home  >  Article  >  Backend Development  >  Does Go Map Iteration Order Depend on Key Insertion Order?

Does Go Map Iteration Order Depend on Key Insertion Order?

Barbara Streisand
Barbara StreisandOriginal
2024-11-22 09:11:11449browse

Does Go Map Iteration Order Depend on Key Insertion Order?

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.

The above is the detailed content of Does Go Map Iteration Order Depend on Key Insertion Order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn