-1

I know the creators of Go decided to randomize the keys of maps so that people didn't assume their order. I guess that could have changed by now but I haven't seen any documentation to that effect.

There's a call to a Linux journal function as follows:

 journal.Send(message string, priority Priority, vars map[string]string) error

(from https://github.com/coreos/go-systemd)

It would be nice to send the vars in a known and controlled order instead of randomized but I don't see how that is possible if you can't really sort a map - all examples I have seen sort the keys into an array and then iterate using the array as a sorted index for the map keys.

Does anyone have any ideas other than rewriting the journal.Send() routine?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user5429087
  • 139
  • 2
  • 10
  • 2
    The [specification says](https://golang.org/ref/spec#For_range): *The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.* Your only option is to sort the keys. – Charlie Tumahai Nov 08 '19 at 05:46
  • well you can just sort the keys dont need to actually sort the map ? Using a diff set or slice – Ravi Chandak Nov 08 '19 at 05:53
  • The map order changes form one iteration to the next, but it's incorrect to assume that the order is *randomized* as stated in the question. The only way to ensure randomized key order is to use something like godoc.org/math/rand#Shuffle on the keys. –  Nov 08 '19 at 06:26

1 Answers1

0

You would need to use a thrid-party library like emirpasic/gods, which does implement:

  • TreeMap: A map based on red-black tree. Keys are ordered with respect to the comparator.
  • Linked Hashmap: A map that preserves insertion-order. It is backed by a hash table to store values and doubly-linked list to store ordering.

But Map alone would remain with randomize keys order.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 1
    The call will only take a map so I don't think these will help in this case but it's nice to know about these, thanks. I'm beginning to think my best option is to see if the author of the journal module would be willing to add a sort on the keys so the vars are listed alphabetically which would give consistency to the output. – user5429087 Nov 08 '19 at 08:39