So I have a problem I'm trying to solve, but I need to iterate over two separate arrays of type []string. Is there a way to accomplish this in Go? Kinda something like this:
for nope, yep := range firstArray, secondArray {
fmt.Println(nope)
fmt.Println(yep)
}
Obviously that doesn't work, just trying to give you an idea of what I'm looking for.
EDIT:
Concatenating or comparing them isn't an option. I need to use the values in both arrays differently.
评论:
djherbis:
muffinz0:
koalainthetree:Thanks! Unfortunately that only works if both arrays are the same size, which won't always be the case. I updated your example to better describe my needs. https://play.golang.org/p/GNJ2tIRgnL
muffinz0:Can you take the length of the longest one and iterate over both of them that way?
fubo:Actually, I just figured it out! https://play.golang.org/p/1Arw3M_KIn
These are pretty different cases.
If you have arrays [1, 2, 3] and [4, 5], parallel iteration will yield two or three iterations:
- x=1, y=4
- x=2, y=5
- ... followed by either skipping x=3 because there isn't a corresponding y value, or having an error, or assigning y to 0, or something else depending on how you code it.
Whereas nested iteration (one for loop inside another) will yield six iterations:
- x=1, y=4
- x=1, y=5
- x=2, y=4
- x=2, y=5
- x=3, y=4
- x=3, y=5
If you want to generate all possible pairings of elements from each array (a Cartesian product), you want nested iteration. If you want to step through both arrays in step with each other, pairing the elements from one array with corresponding elements of the other, you want parallel iteration.
djherbis:muffinz0:
Fwippy:Thank you for your help!
You just need to use two normal loops, one inside the other.
