Nested range loop

package main

import "fmt"

func main() {
        desc := []string{"foo", "bar"}
        exp := []string{"baz", "qux"}

        tmp := make(map[string]string)

        for _, j := range desc {
                for _, n := range exp {
                        tmp[j] = n


This gives me the following output

map[foo:qux bar:qux]

I was expecting

map[foo:baz bar:baz]


Key value pairs must be unique, so the outer range gets foo first, then the inner range gets baz first, so we should have gotten tmp["foo"]=baz and then the inner range iterates over to qux but tmp["foo"] is already set, so tmp["foo"]=qux is rejected, the outer range now iterates over to bar and we follow the same logic above and at last we should have gotten what I was expecting.

Could someone explain, why the result came what it came?

Understood why the result came what it came, tmp["foo"]=qux didn’t get rejected, it got assigned, and so I got the result.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.