Home > Backend Development > Golang > What to do if golang map is not sorted

What to do if golang map is not sorted

藏色散人
Release: 2020-02-04 16:32:47
Original
3181 people have browsed it

What to do if golang map is not sorted

#What should I do if golang map is not sorted?

Example map is as follows. Since the internal storage mechanism of golang map is implemented with the key as hash structure, the order is confusing.

fruits := map[string] int {
    "oranges": 100,
    "apples": 200,
    "banans": 300,
}
Copy after login

If you want it to be in order, you can transfer the key to the slice, sort the slice, and then output:

// Put the keys in a slice and sort it.
var keys []string
for key := range fruits {
keys = append(keys, key)
}
sort.Strings(keys)
// Display keys according to the sorted slice.
for _, key := range keys {
fmt.Printf("%s:%v\n", key, fruits[key])
}
Copy after login

For more go language knowledge, please pay attention to the PHP Chinese websitego language tutorial column.

The above is the detailed content of What to do if golang map is not sorted. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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