Is there a foreach construct in the Go language?
Is there a foreach construct in the Go language?
Yes, there is a foreach
construct in the Go language, which is implemented using the for
keyword followed by the range
keyword. This construct allows you to iterate over elements in various data structures such as slices, arrays, maps, and channels. The syntax for using the foreach
-like construct in Go is as follows:
To iterate over an array or a slice, you can use:
for i, v := range slice {}
to get both the index and the value,for i := range slice {}
to get the index only, orfor _, v := range slice {}
to get the value only.To iterate over a map, you can use:
for key, value := range theMap {}
to get both the key and the value,for key := range theMap {}
to get the key only, orfor _, value := range theMap {}
to get the value only.To iterate over a channel, you use:
for v := range theChan {}
, which will continue to receive from the channel until it is closed.It's important to note that when iterating over a channel using for v := range theChan {}
, the loop will exit gracefully if the channel i...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào