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
Release: 2024-12-07 16:58:15
Original
343 people have browsed it

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])
    }
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template