Home >Backend Development >Golang >How to Iterate Through Go Maps in a Specific Order?

How to Iterate Through Go Maps in a Specific Order?

DDD
DDDOriginal
2024-12-07 16:58:15343browse

How to Iterate Through Go Maps in a Specific Order?

Why Maps Print Out of Order

In Go, maps are unordered collections of key-value pairs. This means that the order of elements in a map is not guaranteed. When you iterate over a map, the elements are returned in an arbitrary order, which can be confusing or problematic if you require a specific order.

Getting Maps in Order

To get maps in order, you can use the sort package. Here's an example:

package main

import (
    "fmt"
    "sort"
)

type monthsType struct {
    no   int
    text string
}

var months = map[int]string{
    1:"January", 2:"Fabruary", 3:"March", 4:"April", 5:"May", 6:"June",
    7:"July", 8:"August", 9:"September", 10:"October", 11:"Novenber", 12:"December",
}

func main(){
    // Create a slice of the map keys
    keys := make([]int, len(months))
    i := 0
    for key := range months {
        keys[i] = key
        i++
    }

    // Sort the slice of keys
    sort.Ints(keys)

    // Iterate over the keys and print the corresponding values
    for _, key := range keys {
        fmt.Println(key, "-", months[key])
    }
}

This code will output the map elements in ascending order of the keys:

1 - January
2 - Fabruary
3 - March
4 - April
5 - May
6 - June
7 - July
8 - August
9 - September
10 - October
11 - Novenber
12 - December

The above is the detailed content of How to Iterate Through Go Maps in a Specific 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