Golang map with range traversal does not guarantee sequential output

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

According to my understanding of the map, the data in the map should be ordered binary tree storage sequence, the normal traversal should also be an orderly traversal and output, but actually tried, but found that not so, on-line check the next, found from Go1 start, the beginning of the traversal of the node is random, of course, to what extent is not clear.

Package Mainimport ("FMT") func main () {x: = Do (map[int]int) for I: = 0; i <; i++ {X[i] = I}for k, V: = range x {FMT . Println (k, V)}}

After the build is executed multiple times, the results of each output are different. Of course, with FMT. PRINTLN ("Map:", x) output is also an unordered result

Referring to http://xhrwang.me/2014/12/25/golang-fundamentals-4-map-range.html, I understand that to create an index for a reference type (Slice,map,channel) at range The index of map is not specified, so it is unordered.


So if you need to guarantee sequential output, I'm using slice.

For a map in Golang, you can also refer to the Https://blog.golang.org/go-maps-in-action


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.