-3
package main

import (
  "fmt"
  "bufio"
  "os"
  "strconv"
)
func main() {
 mp := make(map[int]string)//make a mapping
 in := bufio.NewScanner(os.Stdin)
 fmt.Println("Limit and Enter Strings")
 in.Scan()
 n := in.Text()
 num, err := strconv.Atoi(n)
 fmt.Println(err)
 for i:=0; i<=num;i++ {
   in.Scan()
   mp[i] = in.Text()
 }
 fmt.Println(mp)
}
/* Output Limit and Enter Strings
5
<nil>
one
two
three
four
five
six
map[3:four 4:five 5:six 0:one 1:two 2:three]*/

The program is for making mapping from int to string. When I enter numbers in sequential format it prints a mapping in incorrect order.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gaurav Patel
  • 21
  • 1
  • 5
  • 3
    Possible duplicate of [Why can't Go iterate maps in insertion order?](https://stackoverflow.com/questions/28930416/why-cant-go-iterate-maps-in-insertion-order) – Jonathan Hall Jul 05 '18 at 07:24

2 Answers2

1

Go provides a built-in map type that implements a hash table.

When iterating over a map with a range loop, the iteration order is not specified and is not guaranteed to be the same from one iteration to the next. Since Go 1 the runtime randomizes map iteration order, as programmers relied on the stable iteration order of the previous implementation. If you require a stable iteration order you must maintain a separate data structure that specifies that order. This example uses a separate sorted slice of keys to print a map[int]string in key order:

import "sort"

var m map[int]string
var keys []int
for k := range m {
    keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
    fmt.Println("Key:", k, "Value:", m[k])
}

Link: https://blog.golang.org/go-maps-in-action

Abhilekh Singh
  • 2,845
  • 2
  • 18
  • 24
1

Maps in Go language are not iterated in order (Check out https://blog.golang.org/go-maps-in-action for more on this). It's like a hash. If you need to order, I suggest you consider storing the keys in a slice (in addition to storing the key-value pair in the map) and then when you need to print in the order you entered, iterate over the slice to get the keys, and then retrieve the value for each of the keys from the hash.

Ravi R
  • 1,692
  • 11
  • 16