5

this is my code(golang)

func main() {
    names := []string{"1", "2", "3"}

    for index, name := range names {
        println(index, name)
    }

    myMap := map[string]string{
        "A": "Apple",
        "B": "Banana",
        "C": "Charlie",
    }

    for key, val := range myMap {
        fmt.Println(key, val)
    }
}

and this is result

0 1
B Banana
1 2
2 3
C Charlie
A Apple
  1. Why was it names and myMap mixed?
  2. Why different order of myMap?
Jihun Lee
  • 69
  • 4
  • 4
    Possible duplicate of [golang map prints out of order](http://stackoverflow.com/questions/12108215/golang-map-prints-out-of-order) – Akavall Mar 11 '16 at 02:30
  • 1
    First, the easy one: 2. Map is different order Like @Akavall commented, this is explained is explained in his link. The gist of it is hash tables. 1. This is a curious one, going trough the code of fmt package, it simply writes in a buffer and then writes it. Running your code 100 times in console with different variations runtime.GOMAXPROCS I could not reproduce it and it always printed the full array and then the map, however, your behavior happens when I ran it on IntelliJ with the Go plugin. Are you using it or are you trying on console? You might have stumbled on a plugin bug. – Rodrigo Del C. Andrade Mar 11 '16 at 02:58
  • thank you. I ran it on intellij. – Jihun Lee Mar 11 '16 at 03:15
  • @Akavall: This question is **not** an exact duplicate. Exact duplicate: This question covers exactly the same content as earlier questions on this topic. – peterSO Mar 11 '16 at 12:50

1 Answers1

9

func println

func println(args ...Type)

The println built-in function formats its arguments in an implementation-specific way and writes the result to standard error.

func Println

func Println(a ...interface{}) (n int, err error)

fmt.Println formats using the default formats for its operands and writes to standard output.

fmt.Println writes to standard output (stdout) and println writes to standard error (stderr), two different, unsynchronized files.

Map types

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.

For statements

A "for" statement specifies repeated execution of a block.

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.

Maps elements are unordered. The iteration order is not specified.

peterSO
  • 158,998
  • 31
  • 281
  • 276