Home  >  Article  >  Backend Development  >  Why Does Changing the Indentation in Go Map Assignments Affect the Output Order?

Why Does Changing the Indentation in Go Map Assignments Affect the Output Order?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 05:38:11164browse

Why Does Changing the Indentation in Go Map Assignments Affect the Output Order?

Assignment Order in Go Maps

Consider 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)
}

The output is:

{40.68433 74.39967}
map[Bell Labs:{40.68433 74.39967} test:{12 100}]

However, if a minor change is made to the declaration of the test vertex, by moving the closing curly brace four spaces to the right:

m["test"] = Vertex{
    12.0, 100,
}

The output changes to:

{40.68433 74.39967}
map[test:{12 100} Bell Labs:{40.68433 74.39967}]

The question arises: Why does this slight modification affect the order of the map?

Answer:

The order of a map in Go depends on the underlying hash function used. This hash function is randomized to mitigate denial of service attacks that exploit hash collisions. Refer to the following issue tracker for more information:

http://code.google.com/p/go/issues/detail?id=2630

It's important to note that map order is not guaranteed by the language specification. While current Go implementations maintain a stable order, future revisions might compact maps during garbage collection or other operations, potentially altering the order without the explicit modification of the map by code. Therefore, relying on a specific order for maps is ill-advised.

As stated in the Go specification:

A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type.

The above is the detailed content of Why Does Changing the Indentation in Go Map Assignments Affect the Output 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