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;
}
For example,
package main
import "fmt"
type MyStruct struct {
v1 string
v2 int
}
type MyMap map[string]MyStruct
func main() {
m := MyMap{
"unum": MyStruct{"I", 1},
"duo": MyStruct{"II", 2},
}
fmt.Println("before:")
for k, v := range m {
fmt.Println(k, v)
}
var k string
k = "unum"
if v, ok := m[k]; ok {
v.v1 = "one"
v.v2 = 1
m[k] = v
}
k = "tria"
if v, ok := m[k]; ok {
v.v1 = "III"
v.v2 = 3
m[k] = v
}
fmt.Println("after:")
for k, v := range m {
fmt.Println(k, v)
}
}
Output:
before:
unum {I 1}
duo {II 2}
after:
unum {one 1}
duo {II 2}
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're just trying to find a key in a map, then use the following:
package main
import (
"fmt"
)
type Point struct {
x, y int
}
func main() {
points := make(map[string]*Point)
p := &Point{1, 1}
points["one"] = p
if p1, found := points["one"]; found {
p1.x = 100
}
fmt.Println(p)
}