How do I write Go code that can do something like a map iterator in C++?
typedef std::map<std::string, MyStruct> MyMap;
MyMap::iterator it = myMap.find("key");
if(it!=myMap.end()) {
it->v1 = something;
it->v2 = something;
}
In go, it is pretty easy to iterate over a map using the range clause.
myMap := map[string]int {"one":1, "two":2}
for key, value := range myMap {
// Do something.
fmt.Println(key, value)
}
Could print
one 1
two 2
Note that you iterate in an undefined order over a map, as it is backed by a hash table rather than a tree.
The go language spec describes what the range clause returns, and you can see the effective go page for some more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With