'Is it safe to remove dictionary keys while iterating over it? [duplicate]

I wrote some code which does this, and it is working fine, but when reviewing the code I realize what I did might not have worked in other languages.

To give a contrived example:

dict := map[string]string{ "a": "1", "b": "2" }

for key, val := range dict {
  fmt.Println(val)
   delete(dict, "b")
}

This prints "1" and "2", and when I inspect dict afterward it is { "a": "1" } only.

So, I get the impression that it is safe to do this, but I'm wondering why?

Does range dict create a copy internally?



Solution 1:[1]

As always, the spec is the definitive answer. Under "For statements with range clause", item 3 (emphasis mine):

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.

Solution 2:[2]

verts are just points in space. Essentially each vert is a corner of some triangle (usually more than 1).

To know what the actual triangles are you will look at faces which will have be something like:

[(v1, v2, v3), (v1, v4, v5), ...]

Each tuple in the list includes 3 indices for verts. For example:

verts[v1], verts[v2], verts[v3]

is a triangle in space.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MYousefi