4
4
4utka_pyan2017-06-18 13:46:41
go
4utka_pyan, 2017-06-18 13:46:41

How to do foreach in golang?

My code is now:

func main() {
  x := make(map[string]int)
  x["kid"] = 10
  x["man"] = 9
  x["woman"] = 8

  fmt.Println(x)
}

fmt.Println(x) prints the entire map (associative array) in its entirety. And how to display each element in a loop in turn, referring to it by the name of the key?
I read the answer https://stackoverflow.com/questions/7782411/is-the... but I didn’t understand it, there are 2 examples of the for loop, but it’s not clear to me what to write inside the loops to display on the screen, i.e. . how to refer to the elements is still not clear.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2017-06-18
@4utka_pyan

for i, v := range x {
  fmt.Println(i, v)
}
i -- index
v -- value
If you don't need an index or value, you can specify _
https://play.golang.org/p/SASgm4WSFL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question