I used a map that uses words from a sentence as its keys and integers as the values.
func WordCount(s string) map[string]int {
var m map[string]int
The way how you change the value of the count
variable has nothing to do with the iteration order of the map elements.
There is no "correct" iteration order, the iteration order can be thought of as random (and in current implementation it is random). Quoting from the language spec: For statements:
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.
For more on the topic, check out this answer: Why can't Go iterate maps in insertion order?
The Go Tour uses the Go Playground to provide a code editor and runner. The Go Playground caches the output of the codes you run on it. Running twice the exact same code will just show you the cached output.
If you change your code however, that is "treated" as new code and it will be compiled and ran (and its output will be cached after). And since it is run anew, you may observe a new random order - which you do.
If you change again something in the code, even as insignificant as adding or changing some comment, the output will (may) change again, try it.
For more information on how the Playground is implemented, see blog post Inside the Go Playground.
Quoting the relevant part:
When the front end receives a compilation request it first checks memcache to see if it has cached the results of a previous compilation of that source. If found, it returns the cached response. The cache prevents popular programs such as those on the Go home page from overloading the back ends. If there is no cached response, the front end makes an RPC request to the back end, stores the response in memcache, parses the playback events, and returns a JSON object to the client as the HTTP response (as described above).
Also note that starting with Go 1.12, maps are sorted when printed using the fmt
package (to ease testing), so printing the same map now will always list elements in the same order. The iteration order still remains non-deterministic deliberately.