Câu hỏi phỏng vấn Golang
Câu hỏi

Is there a foreach construct in the Go language?

Câu trả lời

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, or
    • for _, 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, or
    • for _, 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

middle

Gợi ý câu hỏi phỏng vấn

junior

Does Go have exceptions?

senior

What is the difference, if any, in the following two slice declarations, and which one is more preferable?

middle

Is Go an object-oriented language?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào