Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Go have an iterator datatype?

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;
}
like image 276
jinchao Avatar asked Jul 24 '26 17:07

jinchao


1 Answers

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.

like image 76
Alex Reece Avatar answered Jul 26 '26 13:07

Alex Reece